gui design – Making Python script react to keyboard shortcuts

Is there a clean and easy way to capture key combinations with Python only when the script being run is in focus (e.g. the Python intepreter/terminal or IDE window, no global capture)?

Assume that you need to bind 50 different hotkeys – you don’t want to define a function with 10-20 lines of code for each key binding if e.g. a simple dictionary does the job. You also don’t want to be challenged to invent some god-level regex pattern for find & replace in order to write those 50 different functions if e.g. a simple dictionary does the job.

I’ve been trying to hack the keyboard, pynput, and pygame.key packages for over two months, but none of these worked for me. The surprising conclusion is that there doesn’t exist a single Python package yet that offers a simple, concise solution for basic UI tasks that virtually any program that you are using right now is getting done. Just try it: Alt+F4 will close your browser, but not some other applications that you might be running in the background!

So I’m thinking about something along the lines of

import keyboard_package as kb


hotkeys = {'ctrl+c':some_callback, 'ctrl+v':another_callback}

kb.bind_hotkeys(hotkeys)
kb.listener_start(focus=True)

do_something()    # Your production script

kb.listener_stop()
kb.unbind_hotkeys()

If it’s not possible to limit the capture on one window, I’m also fine with having the callback pause the listener, e.g. while a certain very long loop is running and you need to write an e-mail in the meantime without accidentally triggering a core meltdown by doing Ctrl+C and Ctrl+V in Outlook.

Wish list:

  • Capture hotkeys only in focused window
  • Simple, practical, pythonic (I’m not your unpaid GitHub co-dev/beta tester…)