Search code examples
pythontkintereventskeyboard

How to bind keycode of key in Tkinter


In title my problem was described, but here details.

I want to make a binding that can work with all keyboard layouts.

I tried add bind by "(symbol)Key-keycode(symbol)" and just "keycode" but it didn't work. Seems it's accepts only symbols.

I think I need dig deeper into wiki. But I can't find information about it.

Any help would be appreciated.


Solution

  • Here's an example of a general event handler that leverages match (available in Python 3.10 and higher)

    import tkinter as tk
    
    
    def key_handler(event)
        match event.keysym:
            case '<insert your symbol here>':
                ...  # do something
            case '<insert anyther symbol here>':
                ...  # do something else
            case _:  # fallback / default case (yes, this should be an underscore)
                pass  # do nothing
    
    
    root = tk.Tk()
    root.bind('<Key>', key_handler)
    root.mainloop()
    

    This approach is flexible in that it lets you handle any number of '<Key>' events with a single function, but the caveat is that it will fire on every keypress. Any keysym that doesn't have a matching case will fall through. This isn't likely to be a huge performance hit, but it's something to be aware of!