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
相关产品推荐
相关产品推荐

