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

如何让鼠标光标固定在屏幕相对位置并移动后自动归位?

解决鼠标固定在屏幕相对位置并仅在偏离时返回的问题

你当前的代码放进while True循环后,每次都会执行pyautogui.moveTo()——哪怕光标已经精准落在目标位置,这就导致了光标持续“无效移动”的问题。要实现「到位后停止,只有偏离时才自动拉回」的效果,只需要调整判断逻辑,让移动操作仅在光标偏离时触发,同时给循环加个小延迟降低资源占用。

修改后的代码

import pyautogui
import time

# 计算屏幕80%相对位置的目标坐标
screen_width, screen_height = pyautogui.size()
target_x = int(screen_width * 0.8)
target_y = int(screen_height * 0.8)

pyautogui.FAILSAFE = False

while True:
    current_x, current_y = pyautogui.position()
    # 只有光标偏离目标位置时,才执行移动
    if current_x != target_x or current_y != target_y:
        pyautogui.moveTo(target_x, target_y)
    # 10毫秒检查一次,平衡响应速度和CPU占用
    time.sleep(0.01)

关键调整点

  • 优化判断逻辑:把原来的“位置一致就什么都不做”改成“位置不一致才移动”,直接避免了无效的重复移动指令。
  • 添加循环延迟:time.sleep(0.01)让循环不会疯狂占用CPU,同时也能保证光标偏离时的响应速度足够快。
  • 保留相对位置适配:通过pyautogui.size()动态计算目标坐标,自动适配不同分辨率的屏幕,符合你的需求。

可选退出方案

如果需要随时终止程序,可以加个按键退出的逻辑(比如按Esc键):

import pyautogui
import time
import keyboard

screen_width, screen_height = pyautogui.size()
target_x = int(screen_width * 0.8)
target_y = int(screen_height * 0.8)

pyautogui.FAILSAFE = False

while True:
    # 按下Esc键直接退出循环
    if keyboard.is_pressed('esc'):
        break
    current_x, current_y = pyautogui.position()
    if current_x != target_x or current_y != target_y:
        pyautogui.moveTo(target_x, target_y)
    time.sleep(0.01)

(注:使用keyboard库需要先执行pip install keyboard安装)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 14:05:06