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

如何使用Python keyboard模块检测按键,解决按下后重复触发问题

问题根源

你使用的keyboard.is_pressed()接口仅返回当前时刻按键的按下状态,一次普通按键按下的时长约为100~300ms,足够你的while循环执行上百次,因此会重复插入同一个字符。

修复方案

推荐以下两种实现方式,都可以解决重复触发的问题:

方案1:使用keyboard.read_key()(改动最小)

该接口会阻塞等待按键事件,每次按键按下仅返回一次按键值,仅需对原有逻辑做少量修改:

import keyboard

running = True
price = ""

while running:
    key = keyboard.read_key()
    # 过滤按键释放事件,仅处理首次按下
    if keyboard.is_pressed(key):
        if key.isdigit():
            price += key
        elif key == "enter":
            running = False

subtotal = int(price)
print(subtotal)
subtotal = float(subtotal)/100
print("Subtotal: {}".format(subtotal))

方案2:使用事件回调(性能更优)

通过注册按键回调的方式替代轮询,不会占用多余CPU资源空转:

import keyboard

price = ""

def handle_key_press(event):
    global price
    if event.name.isdigit():
        price += event.name
    elif event.name == "enter":
        keyboard.unhook_all()

keyboard.on_press(handle_key_press)
# 阻塞直到监听结束
keyboard.wait()

subtotal = int(price)
print(subtotal)
subtotal = float(subtotal)/100
print("Subtotal: {}".format(subtotal))
注意事项

如果运行时出现权限报错,Linux/macOS系统需要用sudo执行脚本,Windows系统需要用管理员身份运行终端。


内容的提问来源于stack exchange,提问作者Weather512

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 09:54:00