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

Python中locateCenterOnScreen支持region吗?代码报TypeError求解

问题解决与参数确认

错误原因与修复

错误TypeError: cannot unpack non-iterable NoneType object是因为pyautogui.locateOnScreen未找到目标图片时会返回None,直接将None解包给left, top, width, height四个变量会触发该错误。同时原代码中if left is None的判断逻辑无效——若locateOnScreen返回None,解包步骤就会先报错,根本走不到判断分支。

修复后的代码需先捕获返回值,判断非None后再解包:

import time
import pyautogui

time.sleep(1)
# 先获取检测结果,避免直接解包None
screen_result = pyautogui.locateOnScreen('original.png', confidence=0.3)
if screen_result is None:
    print("Not Detected")
else:
    left, top, width, height = screen_result
    print("Detected")
    # 同样处理数字8的中心坐标检测结果
    center_pos = pyautogui.locateCenterOnScreen('number8.png', confidence=0.8, region=(left, top, width, height))
    if center_pos is None:
        print("Number 8 not found")
    else:
        x, y = center_pos
        print("Clicked")
        pyautogui.click(x, y)

参数使用确认

pyautogui.locateCenterOnScreen完全支持配合region参数使用。该函数本质是先调用locateOnScreen定位目标区域,再计算中心坐标;而locateOnScreen原生支持region参数限定查找范围,因此locateCenterOnScreen继承了这一特性。你代码中对region的使用方式是正确的,只要大图检测返回有效区域,就能缩小数字8的查找范围。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 05:25:18