Search code examples
pythontkinterkey-bindings

How do I keybind functions to keys in the keyboard with tkinter


I want to make a function that is triggered by pressing a button with the command (b = Button(command = a)) that will also be able to accept calls from the bind command. The problem is that the bind command sends a variable (event) while command does not. another problem that I have is that I can't figure out how to link functions to physical key pressing on the computer

I have tried b.bind('a',func) to link the physical keys and checked the binding with the enter key

from tkinter import *
def func():
    print("meow")

main = Tk()
bRoll = Button(text = "Hello", command = func)
bRoll.bind('r',func)
bRoll.bind('<Enter>',func)
bRoll.pack()
main.mainloop()

That did not seem to work as it did nothing and I tried to bind to the Enter key (<Enter>) to see what happens and it printed an error because it wanted to send an event to func and it couldn't accept it.


Solution

    1. It does not make any sense to bind a button to an event. Basically what you want is that when you press a key, func() should be called. For that, in this example, you need to bind the event to the main window as in main.bind('r' ,func).
    2. To consume the event, you can add it as a parameter and initialise it to None. Also note that <Enter> means whenever your mouse pointer enters the button widget and not the Enter key. To bind the Enter key, you need to use <Return>.

      import tkinter as tk
      
      def func(event=None):
          tk.Label(main, text="Meow").pack()
      
      main = tk.Tk()
      bRoll = tk.Button(text = "Hello", command = func)
      main.bind('r',func)
      bRoll.bind('<Enter>',func)
      bRoll.pack()
      
      main.mainloop()
      

    Demo

    Note that in the demo above, initially I had pressed the key R.