Capture keys with TKinter with this scenario
The reason the on_press()
command not firing is due to the fact that the .bind()
call is bound to an instance of Canvas
. This means the canvas widget must have the focus for the keypress to register.
Use bind_all
instead of bind
.
Alternatives to fixing this:
Using
mainWindow.bind_all("h", hit)
- to bind the letter h directly to the "hit" button handler function (just make sure the hit function has the signature as follows:def hit(self, event='')
Using
mainWindow.bind_all("h", game.on_press)
- binds the keypress to the whole applicationUsing
root.bind("h", game.on_press)
- binds the keypress to the root window (maybe atoplevel
is more accurate here depending on if there are multiple windows)
Related to catching any key, there are some examples over here about doing that, using the "<Key>"
event specifier: https://tkinterexamples.com/events/keyboard/keyboard.html
whenever you want to combine your mouse and keyboard input with widgets I strongly suggest you to use the built-in .bind()
method. .bind()
can have two values:
- Type of input
- Name of callback function
An example:
entry_name.bind("<Return>", function_name_here)
This will call the function_name_here()
function whenever the Return
or the Enter
key on your keyboard is pressed. This method is available for almost all tk widgets. You can also state key combinations as well as mouse controls.(Ctrl-K, Left-click etc.). If you want to bind multiple key strokes to a certain callback function, then just bind the both with same callback function like this:
entry_name.bind("<Return>", function_name_here)entry_name.bind("<MouseButton-1>", function_name_here)
This will allow you to call the function when either of Return
or Left-click of the mouse are pressed.