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

如何通过指定按键退出Python自动点击器的while循环

解决自动点击器无法通过指定按键退出的问题

问题分析

你的代码里while True循环内只有time.sleep(total_time)和mouse.click(),而time.sleep会让程序完全阻塞指定时长,这段时间里根本没机会执行按键检测逻辑,所以即使你尝试用keyboard.is_pressed也无法触发退出。

修改后的代码(即时响应版本)

import mouse
import keyboard
import time
import os
os.system('cls')

def Config():
    print("Click every")
    hour = int(input("Hour: "))
    minute = int(input("Minute: "))
    second = int(input("Second: "))
    total_time = hour*3600 + minute*60 + second
  
    print("f6 to start and f10 to stop")
    # 定义运行状态标志
    running = True
    
    # 注册F10热键回调,触发时停止循环
    def stop_clicker():
        nonlocal running
        running = False
        print("\n正在停止自动点击器...")
    
    keyboard.add_hotkey('f10', stop_clicker)
    
    keyboard.wait('f6')
    while running:
        # 将长睡眠拆分为多个短间隔,确保能及时响应停止指令
        elapsed_time = 0
        while elapsed_time < total_time and running:
            time.sleep(0.1)
            elapsed_time += 0.1
        # 只有仍在运行状态时才执行点击
        if running:
            mouse.click()
    
    # 清理热键绑定,避免后续冲突
    keyboard.remove_hotkey('f10')
    print("自动点击器已停止")

#def Fastest():

print("    Auto clicker!!!")
print("       By ze")
print("-------------------------")
print("Auto click on desired time or Fastest?")
choose = int(input("""
1. Config (No milliseconds)
2. Fastest
"""))
if choose == 1:
    Config()
# elif choose == 2:
#     Fastest()

#TODO:
# use mouse.click
# make it click with time
# make function fastest start with f1 and stops with f2
# create back up file

关键改动说明

  1. 热键回调机制:通过keyboard.add_hotkey注册F10的触发函数,这个函数在后台线程运行,不受主程序睡眠阻塞影响,能即时修改running状态标志。
  2. 拆分长睡眠:把原本的单次长睡眠拆分成多个0.1秒的短睡眠,每次睡眠后检查running状态,确保在等待点击间隔的过程中能及时响应停止指令,而不是必须等完整个间隔才退出。
  3. 状态检查:每次执行点击前再次确认running状态,避免在睡眠过程中触发停止后仍执行多余的点击操作。

简化版本(响应稍慢)

如果不需要即时响应,也可以用更简单的写法,缺点是必须等当前的睡眠周期结束才会退出:

def Config():
    print("Click every")
    hour = int(input("Hour: "))
    minute = int(input("Minute: "))
    second = int(input("Second: "))
    total_time = hour*3600 + minute*60 + second
  
    print("f6 to start and f10 to stop")
    running = True
    
    def stop_clicker():
        nonlocal running
        running = False
        print("\n正在停止自动点击器...")
    
    keyboard.add_hotkey('f10', stop_clicker)
    
    keyboard.wait('f6')
    while running:
        time.sleep(total_time)
        if running:
            mouse.click()
    
    keyboard.remove_hotkey('f10')
    print("自动点击器已停止")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:20:28