为什么 pyautogui.locateOnScreen("1.png") 在看不到它时会抛出错误?

问题描述 投票:0回答:1

我正在尝试一些Python图像识别,但是每当图像不在屏幕上时,它就会抛出错误,而不是进入else语句。有没有一种方法可以解决这个问题,而不涉及使用 try / except?

from pyautogui import *
import pyautogui

while True:
    if pyautogui.locateOnScreen("1.png", confidence=0.9) != None:
        print("I can see it")
        time.sleep(0.5)
    else:
        print("I cannot see it")
        time.sleep(0.5)
python pyautogui
1个回答
0
投票

文档这么说

从版本 0.9.41 开始,如果定位函数找不到提供的图像,它们将引发

ImageNotFoundException
而不是返回
None

在 Python 中,失败操作出现异常是很正常的,捕获它们并不会产生糟糕的代码。

import pyautogui

while True:
    try:
        pyautogui.locateOnScreen("1.png", confidence=0.9)
    except pyautogui.ImageNotFoundException:
        print("I cannot see it")
    else:
        print("I can see it")

    time.sleep(0.5)

您还可以将其包装在您自己的函数中,该函数在

None
上返回
ImageNotFoundException
。但为了回答你所说的问题,有一个 PyAutoGUI 内置函数,当它找不到图像时不会抛出:
locateAllOnScreen
。它会生成一个生成器,您可以将其与默认值一起传递给
next

import pyautogui

while True:
    if next(pyautogui.locateAllOnScreen("1.png", confidence=0.9), None) is not None:
        print("I can see it")
    else:
        print("I cannot see it")

    time.sleep(0.5)
© www.soinside.com 2019 - 2024. All rights reserved.