Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can't bind KeyPress event to Canvas

Status
Not open for further replies.

dmaggian

Technical User
Jun 30, 2007
4
0
0
US
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 <Button-1> {tk_messageBox -message "%W got button press"}
(bin) 5 % bind .can <KeyPress> {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?
 
I looked into this once before and I recall having convinced myself that keypress didn't make any sense for canvas widgets. There is no relationship between the keyboard and the canvas. Now, if you put a textbox on the canvas, you could probably bind keypress to that.

_________________
Bob Rashkin
 
Hmmm... I can think of lot's of reasons to bind keys to a canvas widget. For example, in the drawing program I'm working on right now I have the ability to select objects to be moved or deleted, I'd like to end the selection by hitting the Escape key, once the objects are selected, I might like to hit them with the Delete key. I'm not using an text, just graphics types primitives.

For now, I'm doing a bind all which allows me to use the escape key inside the canvas (or from anywhere else) but this solution is not ideal; I might want the same key to do something else in other windows.
 
The response I got from Jeff Hobbs on this issue is documented below; This fixes the problem.

This is a classic problem with a few widgets in Tk. The widget has to have *focus* to receive key input. What you can do is:

bind Canvas <ButtonPress-1> {+; focus %W}

to force focus always into canvases, or you can just explicitly set focus some other way.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top