为什么 python 键盘模块命令没有执行?
Why are python keyboard module commands not executing?
我的 python 模块键盘命令工作正常,只要我在无限 while 循环中没有任何其他内容。
只要我在 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()
returns 仅当现在.
按下键时才为真
如果您以正常速度按下和释放按键,则在调用 is_pressed()
时的几毫秒内按键不太可能被按下。
我的 python 模块键盘命令工作正常,只要我在无限 while 循环中没有任何其他内容。
只要我在 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()
returns 仅当现在.
如果您以正常速度按下和释放按键,则在调用 is_pressed()
时的几毫秒内按键不太可能被按下。