Several Modules solve this Problem
Pynput
(pip install pynput
)
Simple module for handling and controlling general inputs
from pynput import keyboard
from pynput.keyboard import Key
def on_press(key):
#handle pressed keys
pass
def on_release(key):
#handle released keys
if(key==Key.enter):
function_x()
with keyboard.Listener(on_press=on_press,on_release=on_release) as listener:
listener.join()
(See pynput docs)
Keyboard (pip install keyboard
)
A simple module for simulating and handling keyboard input
keyboard.add_hotkey('enter', lambda: function_x())
(See Keyboard docs)
Tkinter
Integrated UI Module, can track inputs on focused thread
from tkinter import Tk
root = Tk() #also works on other TK widgets
root.bind("<Enter>", function_x)
root.mainloop()
Be aware: These solutions all use Threading in some way. You might not be able to execute other code after you've started listening for keys.
Helpful threads:
KeyListeners, Binding in Tkinter
feel free to add more solutions