为什么python键盘模块命令不执行?



只要我在无限while循环中没有任何其他内容,我的python模块键盘命令就可以正常工作。

当我在while循环中有其他东西时,keyboard.is_pressed()就不起作用了。

有谁能解释为什么吗?

import keyboard
import time
while True:
if keyboard.is_pressed('a'):
print("/t/tThe 'a' key has been pressed")
time.sleep(0.1)

if keyboard.is_pressed('b'):
print("/t/tThe 'b' key has been pressed")
time.sleep(0.1)

if keyboard.is_pressed('q'):
print("/t/tThe 'q' key has been pressed")
break

for k in range(0,11,1):
print('k is at ' + str(k))
time.sleep(0.1)


print('DONE')

好的。我明白了。问题是while loop运行得非常快。所以为了解释这个问题,事情是,当在while循环的任何迭代中,你的if语句将以非常快的速度处理,但在for循环中,你正在打印10值和0.1睡眠时间,因此在for循环中花费1秒。因此,为了获得按下'a'键的结果,你必须在for循环结束和while循环开始时在非常非常短的时间内按下它,这是不可能的,因此唯一的解决方案是删除for循环。

is_pressed()仅在当前按下键时返回true

如果您以正常速度按下并释放该键,则在调用is_pressed()时的几毫秒内不太可能按下该键。

最新更新