首页 > 解决方案 > Python PyAutoGUI 返回“ImageNotFoundException”,但“except”不识别为异常

问题描述

使用以前版本的 pyautogui,当找不到图像时,返回“None”,所以我过去使用except TypeError:. 但是自从更新(版本 0.9.41)以来,它无法正常工作,因为它返回 ImageNotFoundException,但它不被识别为异常。当我尝试这样做except ImageNotFoundException:时,会出现错误:

[E0712] 捕获不从 Exception 继承的异常:ImageNotFoundException

这个错误应该如何处理?

标签: pythonexceptionpyautoguiexcept

解决方案


这适用于pyautogui 0.9.52python 3.9.0

import pyautogui

# force use of ImageNotFoundException
pyautogui.useImageNotFoundException()

try:
    location = pyautogui.locateOnScreen('foo.png')
    print('image found')
except pyautogui.ImageNotFoundException:
    print('ImageNotFoundException: image not found')

我发现useImageNotFoundException()此页面中的部分locateCenterOnScreen 不会引发 ImageNotFoundException。· 问题 #441 · asweigart/pyautogui。如果useImageNotFoundException()未调用,则locateOnScreen()返回None.


推荐阅读