我正在尝试制作一个倒数到 0,然后开始向上计数的计时器。我正在使用时间和键盘模块。 keyboard来自 PyPi 的模块。
一切都按预期进行,我可以按一个按钮关闭程序,但它只在每次迭代开始时才有效。有没有办法让它在循环运行时随时检查按键情况?我需要使用不同的模块吗?
这是我的代码:
import time
import keyboard
m = 2
s = 0
count_down = True
while True:
if keyboard.is_pressed('q'):
break
print(f"{m} minutes, {s} seconds")
if count_down:
if s == 0:
m -= 1
s = 60
s -= 1
elif not count_down:
s += 1
if s == 60:
m += 1
s = 0
if m == 0 and s == 0:
count_down = False
time.sleep(1)
最佳答案
在这种情况下,使用回调是常见的方法,解决方案如下:
import time
import keyboard
m = 2
s = 0
count_down = True
break_loop_flag = False
def handle_q_button():
print('q pressed')
global break_loop_flag
break_loop_flag = True
keyboard.add_hotkey('q', handle_q_button)
while True:
if break_loop_flag:
break
print(f"{m} minutes, {s} seconds")
if count_down:
if s == 0:
m -= 1q
s = 60
s -= 1
elif not count_down:
s += 1
if s == 60:
m += 1
s = 0
if m == 0 and s == 0:
count_down = False
time.sleep(1)
关于python - 如何在循环期间的任意时刻检查按键按下情况?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60031916/