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

如何让pyautogui.locateOnScreen在不同电脑上统一处理ImageNotFoundException?

问题原因与跨环境一致性解决方案

核心原因

两台电脑行为不一致,本质是pyautogui图像搜索函数的默认行为存在差异,可能由以下因素导致:

  • pyautogui版本不同:部分新版本中locateOnScreen/locateCenterOnScreen的raise_if_not_found参数默认值被调整,工作电脑的版本可能默认开启了异常抛出。
  • 全局配置被修改:工作电脑的代码或环境中可能设置了pyautogui.raiseExceptionOnFail = True,强制找不到图像时抛出异常。
  • 依赖库版本差异:opencv-python、pillow等依赖的版本不一致,导致图像搜索的底层逻辑行为变化。

排查步骤

  • 对比pyautogui版本:在两台电脑的终端执行pip show pyautogui,查看版本号是否一致。
  • 检查全局配置:搜索代码中是否存在pyautogui.raiseExceptionOnFail = True这类全局设置。
  • 测试基础调用:在两台电脑上分别运行以下代码,观察输出:
    import pyautogui
    print(pyautogui.locateOnScreen('不存在的图片.png', confidence=0.6))
    
    如果工作电脑抛出ImageNotFoundException,说明默认行为是抛出异常;个人电脑返回None则符合原逻辑预期。

解决方法

1. 显式指定参数强制返回None

在所有locateOnScreen和locateCenterOnScreen调用中添加raise_if_not_found=False参数,强制找不到图像时返回None,确保跨环境逻辑一致:

import pyautogui
import time
import random
import keyboard

if pyautogui.locateOnScreen('img/run.png', grayscale=False, confidence=0.6, raise_if_not_found=False) is not None:
    locationrun1 = pyautogui.locateCenterOnScreen('img/run.png', grayscale=False, confidence=0.8, raise_if_not_found=False)
    pyautogui.moveTo(locationrun1)
    pyautogui.click()
    print("Run away")

elif pyautogui.locateOnScreen('img/run2.png', grayscale=False, confidence=0.6, raise_if_not_found=False) is not None:
    time.sleep(random.uniform(1.8, 2.1))
    keyboard.press("w")
    locationrun2 = pyautogui.locateCenterOnScreen('img/run2.png', grayscale=False, confidence=0.8, raise_if_not_found=False)
    pyautogui.moveTo(locationrun2)
    pyautogui.click()

2. 统一环境依赖版本

在两台电脑上安装相同版本的依赖,避免版本差异导致的行为变化:

# 示例版本,可根据实际情况调整
pip install pyautogui==0.9.54 opencv-python==4.5.5.62 pillow==9.1.0

3. 异常捕获兜底(可选)

如果上述方法仍有问题,可通过捕获ImageNotFoundException来保证逻辑继续执行:

import pyautogui
import time
import random
import keyboard
from pyautogui import ImageNotFoundException

try:
    run_loc = pyautogui.locateOnScreen('img/run.png', grayscale=False, confidence=0.6)
    if run_loc is not None:
        center = pyautogui.locateCenterOnScreen('img/run.png', grayscale=False, confidence=0.8)
        pyautogui.moveTo(center)
        pyautogui.click()
        print("Run away")
    else:
        raise ImageNotFoundException  # 主动触发异常进入except分支检查run2
except ImageNotFoundException:
    run2_loc = pyautogui.locateOnScreen('img/run2.png', grayscale=False, confidence=0.6, raise_if_not_found=False)
    if run2_loc is not None:
        time.sleep(random.uniform(1.8, 2.1))
        keyboard.press("w")
        center2 = pyautogui.locateCenterOnScreen('img/run2.png', grayscale=False, confidence=0.8, raise_if_not_found=False)
        pyautogui.moveTo(center2)
        pyautogui.click()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 09:10:10