Can't bind KeyPress event to Canvas

Posted by tclmeelmo on 2007-08-06 11:39

I can't seem to bind key press events to the canvas widget.I used the wish shell for the simplest possible test and wrote the following code from the console.

(bin) 2 % canvas .can -bg black
.can
(bin) 3 % pack .can
(bin) 4 % bind .can {tk_messageBox -message "%W got button press"}
(bin) 5 % bind .can {tk_messageBox -message "%W got key press"}

When I click the mouse button inside the canvas I get the message expected but when I press a key inside the canvas nothing happens. Anyone else have this problem?

jeffh
ActiveState Staff
Thu, 2007-08-09 11:52

The widget has to have *focus* to receive key input. What you can do is:

bind Canvas {+; focus %W}

to force focus always into canvases, or you can just explicitly set focus some other way.