将键盘键绑定到函数 - Python KeyListener

Binding a Keyboard Key to a Function - Python KeyListener

"You've pressed the Enter Key!"

每当我按下 Key(z) 时,应该执行该功能:

#Pseudocode:
bind(<Enter>, function_x)

我目前正在开发一个 python 程序,它将 运行 在 恒定循环 中。它 运行 仅在控制台上 (无 GUI),但我仍然需要能够与程序 交互 随时,无需程序要求输入。

几个模块解决了这个问题

Pynput (pip install pynput)

用于处理和控制一般输入的简单模块

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()

(见pynput docs


键盘 (pip install keyboard)

模拟和处理键盘输入的简单模块

keyboard.add_hotkey('enter', lambda: function_x())

(见Keyboard docs


Tkinter

集成UI模块,可以跟踪聚焦线程上的输入

from tkinter import Tk
root = Tk() #also works on other TK widgets
root.bind("<Enter>", function_x)
root.mainloop()

注意:这些解决方案都以某种方式使用线程。开始侦听键后,您可能无法执行其他代码。

有用的线程: KeyListeners, Binding in Tkinter

欢迎补充更多解决方案