使用pynput无法检测按下的按键问题求助
解决pynput检测普通字母按键的问题
你的代码报错是因为Key类仅定义了特殊按键(如Esc、Shift等),普通字母键(比如h)对应的是KeyCode对象,直接调用Key.h会触发AttributeError——Key类根本没有这个属性。
修正方案如下:
- 新增导入
KeyCode类 - 修改按键判断逻辑,用
KeyCode(char='h')匹配普通字母键,同时添加异常处理避免特殊按键引发报错
修正后的完整代码:
from pynput.keyboard import Key, Listener, KeyCode def on_press(key): print(key) try: # 匹配普通字母/字符按键 if key == KeyCode(char='h'): print('done') except AttributeError: # 处理无char属性的特殊按键,比如功能键 pass def on_release(key): print('{0} release'.format(key)) if key == Key.esc: return False # 监听按键直到按下Esc退出 with Listener( on_press=on_press, on_release=on_release) as listener: listener.join()
也可以用更简洁的写法,直接通过key.char属性判断:
def on_press(key): print(key) try: if key.char == 'h': print('done') except AttributeError: pass
注意:必须包裹try-except,因为按下特殊按键(如Esc、Ctrl)时,key对象没有char属性,会触发AttributeError。
内容的提问来源于stack exchange,提问作者W3ke
相关产品推荐
相关产品推荐

