如何在循环中的任何时候检查按键是否按下? [英] How can I check for a key press at any point during a loop?

查看:102
本文介绍了如何在循环中的任何时候检查按键是否按下?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个倒数至0的计时器,然后开始递增计数.我正在使用时间和键盘模块.PyPi的键盘模块.

I am trying to make a timer that counts down to 0, then starts counting up. I am using the time and keyboard modules. The keyboard module from PyPi.

一切正常,我可以按一个按钮来关闭程序,但它仅在每次迭代开始时起作用.有没有办法在循环运行时随时检查按键是否按下?我需要使用其他模块吗?

Everything works as expected, and I am able to press a button to close the program, but it only works at the beginning of each iteration. Is there a way for it to check for a key press at any point while the loop is running? Do I need to be using a different module?

这是我的代码:

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)

推荐答案

在这种情况下,使用回调是常见的方法,这是解决方法:

Using callback is common approach in such case, here is solution:

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)

这篇关于如何在循环中的任何时候检查按键是否按下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆