You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何循环执行PyAutoGUI的locateCenterOnScreen方法直到识别到目标图像

PyAutoGUI 图像识别报错解决方案

错误原因

pyautogui.locateCenterOnScreen 方法在屏幕指定区域未匹配到符合置信度的目标图片时,会返回None而非坐标元组,直接对None做a, b的解包操作就会触发TypeError: 'NoneType' object is not iterable报错。

适配后的实现代码

将识别逻辑封装为循环调用的函数,识别成功后再返回坐标,适配你自定义的置信度、识别区域参数:

import pyautogui

def detect_image(path, confidence=0.6, region=None, duration=0):
    while True:
        image_location = pyautogui.locateCenterOnScreen(path, confidence=confidence, region=region)
        if image_location:
            # 识别成功返回坐标,如果你需要直接点击可以替换为下方注释的代码
            return image_location
            # pyautogui.click(image_location[0], image_location[1], duration=duration)
            # break

# 调用方法获取坐标,避免识别失败直接解包报错
a, b = detect_image('/home/image01.png', confidence=0.6, region=(25,500,1700,570))

可选优化

可在循环中加入休眠逻辑降低CPU占用,同时增加超时判断避免目标图片不存在时程序死锁:

import pyautogui
import time

def detect_image(path, confidence=0.6, region=None, duration=0, timeout=10):
    start_time = time.time()
    while True:
        if time.time() - start_time > timeout:
            raise TimeoutError(f"{timeout}秒内未识别到目标图片")
        image_location = pyautogui.locateCenterOnScreen(path, confidence=confidence, region=region)
        if image_location:
            return image_location
        # 每次识别间隔0.1秒,降低资源消耗
        time.sleep(0.1)

# 调用时可自定义超时时间,单位为秒
a, b = detect_image('/home/image01.png', confidence=0.6, region=(25,500,1700,570), timeout=15)

内容的提问来源于stack exchange,提问作者Tiel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:06:02