Is there a way in tkinter to add multiple keys to a function?

Viewed 36

Example:

import tkinter as tk
root = tk.tk()
def func(key):
   if key == 'a':
      *run code*
   elif key == 'b':
      *run different code* 

root.bind('a','b',func)
root.mainloop()

Basically, if the user hits 'a', something different happens than when they hit 'b'. I know how to do this with two functions, but is there any way to only use one?

1 Answers

Yes you can achive this by binding '<Key>' which is equivalent to any key. Tkinter provides an eventhandler that parse the object event in that object are various information like keysym contained you can use.

import tkinter as tk
root = tk.Tk()
def func(event):
    key = event.keysym
    if key == 'a':
        print('a')
    elif key == 'b':
        print('b') 

root.bind('<Key>',func)
root.mainloop()
Related