为何pyautogui抛出ImageNotFoundException而非返回None?
问题解答:pyautogui.locateOnScreen抛出ImageNotFoundException而非返回None
原因
pyautogui的locateOnScreen方法默认行为是:当找不到匹配的图像时,会抛出ImageNotFoundException异常,而不是返回None。这就是你代码报错的核心原因——和你预期的返回逻辑不符。
解决方法
方法1:修改参数让方法返回None
调用locateOnScreen时添加raiseException=False参数,强制方法在未找到图像时返回None,适配你原本的分支逻辑:
import pyautogui import time # 补充缺失的time模块导入 while True: # 添加raiseException=False参数 match = pyautogui.locateOnScreen('Dassault Falcon 7X.png', confidence=0.8, minSearchTime=5, raiseException=False) if match is not None: print("I can see it!") time.sleep(0.5) else: print("Nope nothing there")
方法2:用异常捕获处理
通过try-except块捕获ImageNotFoundException,实现你的需求:
import pyautogui import time from pyautogui import ImageNotFoundException while True: try: # 找到图像时会执行下面的打印逻辑 pyautogui.locateOnScreen('Dassault Falcon 7X.png', confidence=0.8, minSearchTime=5) print("I can see it!") time.sleep(0.5) except ImageNotFoundException: # 未找到图像时执行这里 print("Nope nothing there")
注意:你的原始代码遗漏了time模块的导入,运行时会触发NameError,上面的修正代码已经补上了这个问题。
内容的提问来源于stack exchange,提问作者mmewtwosaysbye
相关产品推荐
相关产品推荐

