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

循环报错pyscreeze.ImageNotFoundException,如何实现持续检测屏幕图片?

解决屏幕图片持续检测时的异常中断问题

问题根源

pyautogui.locateCenterOnScreen()方法在未匹配到目标图片时,会直接抛出pyscreeze.ImageNotFoundException,导致你的循环被强制中断,无法实现持续检测的需求。

修复方案

方案一:捕获异常继续循环

通过try-except块捕获找不到图片的异常,让脚本在异常发生时继续执行循环:

import pyautogui as pt
import time as t
from pyscreeze import ImageNotFoundException

def check_logout():
    try:
        # 尝试定位图片中心
        logout_image = pt.locateCenterOnScreen('logout.PNG', confidence=.9)
        if logout_image is not None:
            print("Logout image found. Exiting...")
            exit()
    except ImageNotFoundException:
        # 未找到图片时执行的逻辑
        print("Hello")
        t.sleep(1)

while True:
    check_logout()

方案二:先判断存在性再取中心

使用locateOnScreen()方法(未找到图片时返回None,不会抛出异常),确认图片存在后再获取中心坐标:

import pyautogui as pt
import time as t

def check_logout():
    # 先定位图片位置,未找到返回None
    logout_loc = pt.locateOnScreen('logout.PNG', confidence=.9)
    if logout_loc is not None:
        # 可选:获取图片中心坐标
        logout_image = pt.center(logout_loc)
        print("Logout image found. Exiting...")
        exit()
    else:
        print("Hello")
        t.sleep(1)

while True:
    check_logout()

额外注意事项

  • 确保logout.PNG文件和脚本在同一目录下,或者使用绝对路径指定图片位置
  • 若图片匹配困难,可适当降低confidence参数值(比如0.7~0.8),提升匹配容错率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:21:00