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

为何不同电脑运行pyautogui.locateOnScreen会触发ImageNotFoundException?

异常原因分析
  • 核心问题是两台设备上pyautogui的图像匹配失败行为不一致:其中一台在找不到目标图像时返回None,另一台则直接抛出ImageNotFoundException。
  • 即便库版本、屏幕分辨率一致,系统的屏幕色彩配置(如Gamma值、色彩空间)、底层依赖库(如OpenCV)的编译参数差异,都可能导致这种行为区别。
  • 原代码将整个if-elif逻辑放在同一个try块内,当第一个locateOnScreen抛出异常时,程序直接进入except分支,完全跳过了elif的判断逻辑,这就是异常出现的直接诱因。
正确修复方案

方案1:全局配置pyautogui,禁用图像未找到异常

在代码开头添加配置,让pyautogui在找不到图像时返回None而非抛出异常,这样原有的if-elif逻辑就能正常执行:

import pyautogui
import time
import random
from colorama import Fore, Style
from PIL import ImageGrab

# 关键配置:关闭图像未找到时的异常抛出,改为返回None
pyautogui.useImageNotFoundException(False)

try:
    # 预获取匹配结果,避免重复调用locateOnScreen提升效率
    next_match = pyautogui.locateOnScreen('img/next.png', grayscale=False, confidence=0.8)
    if next_match is not None:
        time.sleep(random.uniform(0.5, 0.8))
        pyautogui.press("z")
        print(f"{Fore.YELLOW}Action.{Style.RESET_ALL}")
    else:
        close_match = pyautogui.locateOnScreen('img/close.png', grayscale=False, confidence=0.8)
        if close_match is not None:
            locationIVS = pyautogui.locateCenterOnScreen('img/close.png', confidence=0.8)
            screenshot = ImageGrab.grab()
            # 可补充截图保存逻辑:screenshot.save("close_screenshot.png")
except Exception as e:
    print(f"An error occurred: {e}")

方案2:单独捕获每个图像匹配的异常

如果不想全局修改配置,可以给每个locateOnScreen调用单独添加异常捕获,确保一个匹配失败不会影响另一个分支的执行:

import pyautogui
import time
import random
from colorama import Fore, Style
from PIL import ImageGrab

try:
    next_found = False
    try:
        if pyautogui.locateOnScreen('img/next.png', grayscale=False, confidence=0.8) is not None:
            time.sleep(random.uniform(0.5, 0.8))
            pyautogui.press("z")
            print(f"{Fore.YELLOW}Action.{Style.RESET_ALL}")
            next_found = True
    except pyautogui.ImageNotFoundException:
        pass

    if not next_found:
        try:
            if pyautogui.locateOnScreen('img/close.png', grayscale=False, confidence=0.8) is not None:
                locationIVS = pyautogui.locateCenterOnScreen('img/close.png', confidence=0.8)
                screenshot = ImageGrab.grab()
        except pyautogui.ImageNotFoundException:
            pass
except Exception as e:
    print(f"An error occurred: {e}")

临时方案的问题

你当前的临时方案虽然能运行,但存在明显缺陷:

  • 重复调用locateOnScreen和locateCenterOnScreen,浪费系统资源;
  • 使用空except捕获所有异常,会掩盖其他潜在错误(如文件路径错误、权限问题);
  • 强制开启grayscale=True可能降低匹配精度,导致误判或漏判。

内容的提问来源于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:43:48