3

So guys I'm new to GUIs in Python and I've been trying to understand the envents process, here's my code, and the intention that whenever I press the 'a' key it should print "key pressed'. But it won't work for me.

#!/usr/bin/env python3
# -*-coding:UTF-8 -*

from tkinter import *

root = Tk()

def callback(event):
    print("key pressed")

canvas = Canvas(root, width=100, height=100, bg='blue')
canvas.bind("a", callback)
canvas.pack()

root.mainloop()

1 Answer 1

5

It doesn't execute the callback function because the focus of the program is on the Tk element. If you replace that line with root.bind("a", callback), it will work as you expect.

The problem is that the canvas element doesn't receive the focus when you click on it like other widgets as Entry, so it will only respond to keydown events if you call first canvas.focus_set().

Sign up to request clarification or add additional context in comments.

1 Comment

Note that you can also bind <1> to do the focus_set, which will allow you to click in the canvas and then type a character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.