Capture keys with TKinter with this scenario Capture keys with TKinter with this scenario tkinter tkinter

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:

  1. 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='')

  2. Using mainWindow.bind_all("h", game.on_press) - binds the keypress to the whole application

  3. Using root.bind("h", game.on_press) - binds the keypress to the root window (maybe a toplevel 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:

  1. Type of input
  2. 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.