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

为何坐标列表迭代触发TypeError:list indices必须为整数而非Box

问题

通过pyautogui定位图片坐标存入列表getlist后,遍历列表点击对应坐标时触发错误。相关代码:

getlist = []

if keyValue == False:
     while True:
         if keyboard.is_pressed(key):
            for i in range(0,21):
                # search coords
                if i != 0:
                    start = pyautogui.locateOnScreen(f'C:/Users/Marv/Desktop/PYTHON/new folder/{i}.png', confidence=0.9)
                    # coord to list
                    getlist.append(start)
                    print(f'{i} = {getlist[i-1]}')
            for c in getlist:
                if c == 0:
                    pyautogui.click(getlist[c])
                    time.sleep(0.5)
                else:
                    pyautogui.click(getlist[c])
                    time.sleep(0.7)
                    pyautogui.click(getlist[c])
                # print(getlist[c])
            keyValue = True

触发的错误信息:

pyautogui.click(getlist[c])
                    ~~~~~~~^^^
TypeError: list indices must be integers or slices, not Box

疑问:为何列表中的坐标不可迭代且提示该对象为Box类型?

原因与修复方案

核心原因

  1. locateOnScreen返回的是Box对象而非整数:pyautogui找到匹配图片时,locateOnScreen会返回一个Box类实例(包含left、top、width、height四个属性),不是整数。你遍历getlist时,c本身就是这个Box对象,却用它当列表索引getlist[c],自然报错——列表索引只能是整数或切片,不能是Box对象。
  2. 遍历逻辑混淆:你搞混了"遍历列表元素"和"遍历索引"的逻辑,for c in getlist拿到的是列表里的每个Box对象,不是索引值。

修复步骤

  1. 直接用Box对象点击:pyautogui.click()可以直接接收Box对象作为参数,不需要再通过列表索引取值。
  2. 处理未找到图片的情况:如果locateOnScreen没找到匹配,会返回None,必须先判断,避免后续点击报错。
  3. 修正无效条件:原代码里if c == 0完全不成立(c是Box或None,永远不等于0),需要换成实际有效的判断逻辑。

修复后的示例代码:

import pyautogui
import keyboard
import time

getlist = []
keyValue = False
key = "your_key_here"  # 替换成实际触发按键

if not keyValue:
    while True:
        if keyboard.is_pressed(key):
            # 直接从1开始循环,去掉冗余的i!=0判断
            for i in range(1, 21):  
                start = pyautogui.locateOnScreen(f'C:/Users/Marv/Desktop/PYTHON/new folder/{i}.png', confidence=0.9)
                getlist.append(start)
                print(f'{i} = {start}')
            
            for c in getlist:
                if c is None:
                    print("未找到对应图片,跳过")
                    continue
                # 直接使用Box对象点击
                pyautogui.click(c)
                time.sleep(0.5)
                pyautogui.click(c)
                time.sleep(0.7)
            
            keyValue = True
            break  # 退出循环,避免重复触发

补充说明

  • Box对象支持迭代,也可以用pyautogui.center(c)获取图片中心坐标,再传入click(),效果一致。
  • 原代码的while循环没有退出条件,修复后添加break避免无限循环。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:35:03