如何加速Python鼠标画圆脚本并实现键盘中断循环?
优化鼠标画圆脚本:提速与键盘中断实现
解决鼠标移动过慢的问题
- 原脚本中极小的
duration值无法被pyautogui识别,反而会引入无效延迟,直接将duration设为0即可触发瞬间移动,这是pyautogui支持的最快移动速度。 - 调整
steps参数(示例设为60),平衡圆的平滑度与绘制速度,步数越多圆越流畅,同时不会因步数过多拖慢整体节奏。 - 简化角度计算逻辑,用
math.radians()直接转换角度为弧度,减少不必要的运算开销。
实现键盘中断循环
- 使用
pynput库监听键盘输入,按下Esc键即可终止循环。先安装依赖:pip install pynput - 开启独立线程处理键盘监听,避免阻塞画圆的主循环,保证响应实时性。
完整优化代码
import pyautogui as pg import math from pynput import keyboard import threading # 全局标志控制循环状态 running = True def on_press(key): global running # 按下Esc键停止循环并结束监听 if key == keyboard.Key.esc: running = False return False # 启动键盘监听后台线程 listener_thread = threading.Thread(target=lambda: keyboard.Listener(on_press=on_press).start()) listener_thread.daemon = True listener_thread.start() # 基础参数设置 screen_size = pg.size() radius = 100 move_duration = 0 # 瞬间移动 circle_steps = 60 center_x = screen_size[0] / 2 center_y = screen_size[1] / 2 def get_circle_point(angle): radian = math.radians(angle) x = radius * math.sin(radian) y = radius * math.cos(radian) return (x, y) def draw_circle(): angle = 0 step = 360 / circle_steps while angle < 360: # 避免重复绘制起点 x, y = get_circle_point(angle) pg.moveTo(center_x + x, center_y - y, duration=move_duration) angle += step # 持续画圆直到触发中断 while running: draw_circle()
使用说明
- 安装依赖库:
pip install pyautogui pynput - 运行脚本后,鼠标会在屏幕中心持续绘制圆形轨迹
- 按下键盘上的
Esc键,脚本将立即停止运行
内容的提问来源于stack exchange,提问作者Vincent Gallo
相关产品推荐
相关产品推荐

