Python Tkinter Canvas Cannot Bind Keyboard

I ran a small script like this

from Tkinter import *
root = Tk()
def callback(event):
    print "callback"
w = Canvas(root, width=300, height=300)
w.bind("<Key>", callback)
w.pack()
root.mainloop()

However, the keyboard event is not handled in my situation (I am using python 2.7 in window 7)

If i use

w.bind("<Button-1>", callback)

Everything is working fine.

So that really puzzles me. Please tell me why this is happening, thanks in advance.

+5
source share
3 answers

Key binding only works when the widget with the keyboard focus receives a key event. By default, the canvas does not receive keyboard focus. You can focus it on the method focus_set. Usually you do this in a snap on a mouse button.

Add the following binding to your code, then click on the canvas and your key bindings will start working:

w.bind("<1>", lambda event: w.focus_set())
+6

" , ", :

http://ubuntuforums.org/showthread.php?t=1378609

, , . :

w.focus_set()
w.bind(<Key>, callback)
+2

tkinter , "Enter", , . , canvas.focus_set, , , , , , .

This will work even if the canvas loses focus (for example, entering text into another widget), because when the mouse enters the canvas again, it will restore focus.

+1
source

All Articles