You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pynput无法检测按下的按键问题求助

解决pynput检测普通字母按键的问题

你的代码报错是因为Key类仅定义了特殊按键(如Esc、Shift等),普通字母键(比如h)对应的是KeyCode对象,直接调用Key.h会触发AttributeError——Key类根本没有这个属性。

修正方案如下:

  1. 新增导入KeyCode类
  2. 修改按键判断逻辑,用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 05:30:47