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

Python报TypeError: 'NoneType'对象不可下标,未使用sort等方法

错误原因分析

你的报错根源在于**pyautogui.locateOnScreen('allbutton.png')返回了None**,导致后续调用pyautogui.center(allbutton)时,函数内部尝试对None进行下标访问(coords[0]、coords[1]等),触发TypeError: 'NoneType' object is not subscriptable。

为什么会返回None?

  • 脚本启动时就执行了allbutton = pyautogui.locateOnScreen('allbutton.png'),这时候游戏界面里的"ALL"按钮还没显示(比如你还没按'c'打开背包),PyAutoGUI找不到对应的图片,就会返回None。
修复方案

1. 延迟按钮定位时机

不要在脚本开头就定位allbutton,而是在打开背包之后(也就是执行pyautogui.press('c')之后)再去查找按钮:

if keyboard.is_pressed('m') is True:
    while keyboard.is_pressed('q') is False:

        if pyautogui.pixel(1815, 1021) != (255, 185, 44):  # If empty
            if pyautogui.pixel(1493, 93) != (255, 255, 255):  # Check if no all option is not found
                pyautogui.press('c')  # Press c for inventory
                # 在这里才定位按钮,此时背包已打开,按钮应该存在
                allbutton = pyautogui.locateOnScreen('allbutton.png')
                # 增加判断,确保找到按钮再操作
                if allbutton is not None:
                    allbutton_centre = pyautogui.center(allbutton)
                    click(allbutton_centre)
                else:
                    print("找不到ALL按钮")
            # 后续代码...

2. 增加重试机制

为了避免因为识别延迟导致找不到图片,可以加入循环重试,直到找到按钮或超时:

def find_button_with_retry(image_path, timeout=5):
    start_time = time.time()
    while time.time() - start_time < timeout:
        button = pyautogui.locateOnScreen(image_path)
        if button is not None:
            return button
        time.sleep(0.1)
    return None

# 使用示例
allbutton = find_button_with_retry('allbutton.png')
if allbutton:
    allbutton_centre = pyautogui.center(allbutton)
    click(allbutton_centre)
else:
    print("超时,未找到ALL按钮")

3. 检查图片匹配度

确认allbutton.png的截图和游戏中的按钮完全一致,避免因为分辨率、缩放、颜色差异导致识别失败。可以尝试调整locateOnScreen的confidence参数(需要安装opencv-python),降低匹配精度要求:

allbutton = pyautogui.locateOnScreen('allbutton.png', confidence=0.8)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 02:55:23