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

如何让代码全程持续检测按钮输入并触发对应操作?

实时检测按钮状态并响应的解决方案

你的问题核心在于原代码里的time.sleep(1)——这个函数会完全阻塞程序运行,导致按钮检测逻辑只能在每轮睡眠结束后才执行一次,自然没法实时响应按键操作。要实现同时持续检测按钮+运行显示逻辑,得把阻塞式的睡眠换成非阻塞的时间判断方式。

下面是修改后的代码:

import time

def main():
    clear()
    display.set_pen(GREEN)
    display.text("Blink of an Eye", 30, 25, 240, 5)
    display.update()
    time.sleep(2)
    clear()
    
    # 记录显示切换的时间点,控制轮播间隔
    last_switch_time = time.time()
    # 标记当前显示的提示类型(0=How To Play,1=Play)
    current_display = 0
    display_interval = 1  # 显示切换间隔设为1秒

    while True:
        # 优先检测按钮状态,确保按键能被立即响应
        if button_b.is_pressed():
            clear()
            play()
            # 返回主界面后重置显示状态
            last_switch_time = time.time()
            current_display = 0
            continue
        elif button_a.is_pressed():
            clear()
            howToPlay()
            last_switch_time = time.time()
            current_display = 0
            continue
        
        # 非阻塞式判断是否需要切换显示内容
        current_time = time.time()
        if current_time - last_switch_time >= display_interval:
            clear()
            if current_display == 0:
                display.set_pen(YELLOW)
                display.text('''How To Play:
Press 'A' ''', 15, 35, 240, 4)
                current_display = 1
            else:
                display.set_pen(MAGENTA)
                display.text('''Play:
Press 'B' ''', 15, 35, 240, 4)
                current_display = 0
            display.update()
            last_switch_time = current_time

关键改动说明:

  • 用time.time()记录每次显示切换的时间戳,通过计算时间差判断是否需要切换内容,全程不会阻塞程序
  • 把按钮检测放在循环最开头,确保只要按键被按下,就能立刻触发对应逻辑,不会被显示逻辑延迟
  • 从play()或howToPlay()返回后,重置显示状态,避免回到主界面时出现显示混乱

修改后,程序会在每一轮循环中都检查按钮状态,同时按设定间隔切换显示内容,用户任何时候按下按钮都能得到即时响应。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 16:24:54