如何在已用time.sleep的Python脚本中12秒后执行光标归位动作
解决方案
你需要在点击线程中记录启动时间,通过时间差判断触发光标归位,同时保证归位操作只执行一次,避免阻塞正常点击流程。以下是修改后的代码:
import time import threading import random from pynput.mouse import Controller, Button from pynput.keyboard import Listener, KeyCode TOGGLE_KEY = KeyCode(char="1") TARGET_POS = (759, 718) # 目标归位坐标,单独提取方便修改 clicking = False mouse = Controller() start_time = None # 记录点击启动的时间 has_reset_position = False # 标记是否已执行归位操作 def clicker(): global start_time, has_reset_position while True: if clicking: # 执行右键点击 mouse.click(Button.right, 1) # 生成随机坐标并移动光标 a = random.randint(732, 1215) b = random.randint(176, 500) mouse.position = (a, b) # 检查是否需要触发12秒归位 if not has_reset_position: current_time = time.time() if current_time - start_time >= 12: mouse.position = TARGET_POS has_reset_position = True # 标记已完成归位,避免重复执行 time.sleep(0.001) else: # 停止点击时重置计时和标记,保证下次启动重新触发逻辑 start_time = None has_reset_position = False time.sleep(0.1) # 未点击时降低循环频率,减少资源消耗 def toggle_event(key): global clicking, start_time if key == TOGGLE_KEY: clicking = not clicking if clicking: # 启动点击时记录当前时间戳 start_time = time.time() # 初始位置直接设为目标坐标(可选,根据需求调整) mouse.position = TARGET_POS # 启动点击线程 click_thread = threading.Thread(target=clicker) click_thread.start() # 监听键盘触发事件 with Listener(on_press=toggle_event) as listener: listener.join()
关键修改说明
- 新增
start_time变量记录点击启动的时间戳,通过计算时间差实现非阻塞式计时,避免使用time.sleep(12)导致点击中断 - 新增
has_reset_position标记位,确保12秒后的归位操作仅执行一次 - 停止点击时重置计时和标记,保证下次启动点击时重新触发12秒归位逻辑
- 优化随机坐标生成逻辑(原代码的for循环无意义,直接生成一次即可)
- 未点击状态下添加
time.sleep(0.1)降低循环频率,减少CPU占用
内容的提问来源于stack exchange,提问作者user24875916
相关产品推荐
相关产品推荐

