Skip to main content
 首页 » 编程设计

Python PyAutoGUI 返回 "ImageNotFoundException",但 "except"不将其识别为异常

2024年12月31日414tuyile006

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

[E0712] Catching an exception which doesn't inherit from Exception: ImageNotFoundException

应该如何处理这个错误?

请您参考如下方法:

这适用于 pyautogui 0.9.52 和 python 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 doesn't raise ImageNotFoundException. · Issue #441 · asweigart/pyautogui .如果未调用 useImageNotFoundException(),locateOnScreen() 只会返回 None。