pythontkintercross-platformglobal-hotkey

How bind/map global hotkey when using Python Tkinter?


I want to bind/map a global hotkey, which also works when application window is minimized and user not focused on it. I'm looking for a cross-platform way. Can I do this using Tkinter?


Solution

  • With tkinter, if the window does not have keyboard focus it won't receive the keypress events so you won't be able to do what you want.

    However, with pynput you can listen to the keypress events:

    from pynput.keyboard import Listener
    
    def on_press(key):
        print("PRESSED", key)
    
    
    with Listener(on_press=on_press) as listener:
        listener.join()
    

    This should be cross-platform (but with some patform specific limitations).