
pyautogui自0.9.41版起,`locateonscreen()`在未找到图像时默认抛出`imagenotfoundexception`而非返回`none`,因此直接用`if ... != none`判断会中断程序;本文介绍`try/except`、`locateallonscreen + next()`及封装函数三种健壮处理方式。
PyAutoGUI 的图像定位功能(如 locateOnScreen())设计上遵循“显式优于隐式”的 Python 哲学:当目标图像未被识别时,它主动抛出 pyautogui.ImageNotFoundException 异常,而非静默返回 None。这种设计能帮助开发者及时发现图像路径错误、截图质量差、屏幕缩放不匹配或 confidence 阈值设置过高等真实问题,避免因误判 None 而掩盖逻辑缺陷。
虽然问题中希望“不使用 try/except”,但需明确:捕获 ImageNotFoundException 是官方推荐且最直观的惯用做法。它语义清晰、性能高效、符合 Python 异常处理最佳实践:
import pyautogui
import time
while True:
try:
# 若找到图像,返回 Box 对象(left, top, width, height)
location = pyautogui.locateOnScreen("1.png", confidence=0.9)
print("I can see it")
except pyautogui.ImageNotFoundException:
print("I cannot see it")
time.sleep(0.5)若坚持避免 try/except,可借助 locateAllOnScreen() —— 它返回一个生成器(generator),在无匹配时为空,不会抛异常。配合内置 next() 函数并提供默认值 None,即可安全判断:
import pyautogui
import time
while True:
# locateAllOnScreen() 总是返回生成器;next(..., None) 在生成器为空时返回 None
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)⚠️ 注意:locateAllOnScreen() 会扫描全屏所有匹配项,性能略低于 locateOnScreen()(后者找到首个即停)。若仅需检测存在性,此方案可行;但若后续还需坐标信息,建议仍用 try/except 并保留 location 变量。
更进一步,可封装一个兼容旧行为的工具函数,统一抽象异常逻辑:
def safe_locate(image_path, **kwargs):
"""安全调用 locateOnScreen,找不到时返回 None"""
try:
return pyautogui.locateOnScreen(image_path, **kwargs)
except pyautogui.ImageNotFoundException:
return None
# 使用示例
while True:
if safe_locate("1.png", confidence=0.9):
print("I can see it")
else:
print("I cannot see it")
time.sleep(0.5)总结:不要将异常视为“错误”,而应视其为 PyAutoGUI 提供的关键反馈机制。优先采用 try/except 方案;若需链式调用或函数式风格,locateAllOnScreen + next() 是简洁替代;长期项目中,封装 safe_locate 可提升代码复用性与可读性。同时务必检查图像文件路径、DPI 缩放设置(Windows/macOS)、后台窗口遮挡及 confidence 参数(建议 0.7–0.95 区间调试)。










