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

PyAutoGUI定位屏幕图片后如何先移动到图片左上角再执行相对移动

问题示意图

问题说明
  • 已实现屏幕中ScheduledBy.png图片的定位、鼠标相对移动功能,但无法控制鼠标先移动到定位图片的左上角位置
  • 原有代码运行时,鼠标仅以自身当前所在位置为基准执行相对移动,无法以目标图片左上角为起点做坐标偏移
  • 预期效果:定位到目标图片后,先将鼠标移动到该图片左上角,再相对该位置偏移(277,25)坐标后执行点击操作

原有问题代码如下:

from pyautogui import *

import pyautogui
import time
import keyboard
import random  
import win32api, win32con

    
if pyautogui.locateOnScreen('ScheduledBy.png', confidence=0.9) !=None:
    # need to move x277 y25 relative to top left of 'ScheduledBy.png'
    pyautogui.moveRel(277,25)
    time.sleep(.1)
    pyautogui.click()
    
    
else:
    print("No")
解决方法

pyautogui.locateOnScreen()匹配成功时会返回一个Box对象,包含匹配区域的left(左上角x轴绝对坐标)、top(左上角y轴绝对坐标)、width(区域宽度)、height(区域高度)四个属性,直接读取这两个坐标值,用绝对移动方法moveTo替代相对移动moveRel即可实现需求。

修正后代码:

from pyautogui import *
import pyautogui
import time
import keyboard
import random  
import win32api, win32con

target_pos = pyautogui.locateOnScreen('ScheduledBy.png', confidence=0.9)
if target_pos is not None:
    # 计算目标点击绝对坐标:图片左上角坐标 + 自定义偏移量
    click_x = target_pos.left + 277
    click_y = target_pos.top + 25
    # 移动到目标位置,可通过duration参数设置鼠标移动耗时,操作更自然
    pyautogui.moveTo(click_x, click_y, duration=0.1)
    time.sleep(0.1)
    pyautogui.click()
else:
    print("No")

注意事项

  • 使用confidence参数需要提前安装opencv-python依赖,否则会触发参数报错
  • 确保ScheduledBy.png模板图片和运行脚本的路径一致,避免匹配失败
  • 如果不需要展示鼠标移动过程,可以去掉duration参数,鼠标会直接跳转到目标位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 15:48:43