修改前报错的原因是没有找到图片文件,修改后报错的原因是没有在屏幕上找到图片。我查阅了 pyautogui 的官方文档,发现有一个更新影响了 locateOnScreen 函数。
The Locate Functions
NOTE: As of version 0.9.41, if the locate functions can’t find the provided image, they’ll raise ImageNotFoundException instead of returning None.
提示:自 0.9.41 版本起,如果用来定位图片位置的函数找不到提供的图片,它们将会引发 ImageNotFoundException 错误,而不是返回 None 。
原文出处:https://pyautogui.readthedocs.io/en/latest/screenshot.html
因此,你必须使用 try 语句捕获异常,不能使用 if 语句
- import pyautogui
- print("程序开始执行")
- try:
- location = pyautogui.locateOnScreen('QQ.png', confidence=0.9)
- print("图片检测完成")
- except ImageNotFoundException:
- print('没找到')
- else:
- print('找到了')
复制代码