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

Python键盘检测异常:按一次Q键后程序持续执行循环求助

Python程序无限循环与误触发问题修复

问题1:按下一次"q"后程序反复执行click_x_box

原因

主循环里的keyboard.is_pressed("q")是实时检测按键状态,当click_x_box执行耗时较长时,哪怕松开q键,循环仍可能因执行过快误判按键状态,或者按键输入缓存残留,导致函数被反复调用。而且原逻辑没有在松开q键时停止执行的机制。

修复方案

改用按键事件监听控制执行状态,通过全局标志位is_running决定是否执行清理操作,确保按下q时启动,松开时停止。

问题2:无纯红色像素时click函数仍执行

原因

原像素检测条件pyautogui.pixel(X_axis, Y_Axis_top)[0] == 255 and pyautogui.pixel(X_axis, Y_Axis_top)[1] != 255过于宽松——只要红色通道为255、绿色通道非255就会触发,像橙色(255,165,0)、粉色(255,192,203)这类颜色都会被误判成目标红色(255,0,0)。

修复方案

直接检测像素是否等于纯红色元组(255, 0, 0),同时避免重复调用pyautogui.pixel提升性能。


修改后的完整代码

import win32api
import win32con
import time
import pyautogui
import keyboard

# 全局标志位:控制清理操作的启停
is_running = False

def click(x,y):
    win32api.SetCursorPos((x,y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
    time.sleep(0.05)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)

def click_x_box(Box_x_axis, X_axis, Y_Axis_top, Y_Axis_bottom):
    #[从顶部开始检测纯红色像素]
    current_y = Y_Axis_top
    while current_y <= Y_Axis_bottom:  # 增加边界判断,防止无限循环
        pixel_color = pyautogui.pixel(X_axis, current_y)
        if pixel_color == (255, 0, 0):
            click(Box_x_axis, current_y)
            current_y += 19
        else:
            break  # 非纯红色则退出循环
    print("finished top-down loop")

    #[从底部开始检测纯红色像素]
    current_y = Y_Axis_bottom
    while current_y >= Y_Axis_top:  # 增加边界判断
        pixel_color = pyautogui.pixel(X_axis, current_y)
        if pixel_color == (255, 0, 0):
            click(Box_x_axis, current_y)
            current_y -= 19
        else:
            break
    print("finished bottom-up loop")

def on_q_press(event):
    global is_running
    is_running = True
    print("q is pressed, starting clearing")

def on_q_release(event):
    global is_running
    is_running = False
    print("q is released, stopping clearing")

def main():
    print("Hold 'q' to start clearing out the page of red")
    # 注册按键监听事件
    keyboard.on_press_key("q", on_q_press)
    keyboard.on_release_key("q", on_q_release)
    
    while True:
        if is_running:
            # 替换为你实际使用的坐标参数值
            click_x_box(Box_x_axis, X_axis, Y_Axis_top, Y_Axis_bottom)
        time.sleep(0.1)  # 降低CPU占用

if __name__ == "__main__":
    main()

额外优化说明

  • 用current_y变量替代直接修改传入的坐标参数,避免后续调用时参数异常
  • 添加上下边界判断,防止因像素检测逻辑错误导致无限循环
  • 主循环增加time.sleep(0.1),降低程序运行时的CPU使用率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 21:06:22