使用pyautogui出现TypeError报错,如何修复代码?
问题修复方案
错误原因
pyautogui.locateCenterOnScreen在屏幕上找不到目标图像(yellow.png)时,会返回None。直接用x, y = ...解包None,必然触发TypeError: cannot unpack non-iterable NoneType object。- 原代码里的
if x.size == 0完全错误——如果定位成功,x是整数类型的坐标值,根本不存在size属性。
修正后的代码
import pyautogui # 先获取定位结果,避免直接解包None center_pos = pyautogui.locateCenterOnScreen('yellow.png', confidence=0.8) if center_pos is None: print("Not Detected") pyautogui.click(1280, 720) else: x, y = center_pos print("Detected") pyautogui.click(x, y)
额外说明
- 如果还是经常定位失败,可适当降低
confidence参数值(比如调到0.7),或者检查yellow.png是否和屏幕上的目标完全匹配(尺寸、颜色是否一致)。 - 确保已安装
opencv-python,因为confidence参数依赖该库,未安装则执行pip install opencv-python。
内容的提问来源于stack exchange,提问作者Jay Jeong
相关产品推荐
相关产品推荐

