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

如何加速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()

使用说明

  1. 安装依赖库:pip install pyautogui pynput
  2. 运行脚本后,鼠标会在屏幕中心持续绘制圆形轨迹
  3. 按下键盘上的Esc键,脚本将立即停止运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 17:05:16