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

使用pyautogui出现TypeError报错,如何修复代码?

问题修复方案

错误原因

  1. pyautogui.locateCenterOnScreen在屏幕上找不到目标图像(yellow.png)时,会返回None。直接用x, y = ...解包None,必然触发TypeError: cannot unpack non-iterable NoneType object。
  2. 原代码里的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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 05:31:09