首页 > 解决方案 > 仅遍历数组的某个部分的正确方法?

问题描述

Traceback (most recent call last):
 File "C:/Users/yaahy/PycharmProjects/Testing/testing1.py", line 45, in 
<module>
    clicktheshit()
  File "C:/Users/yaahy/PycharmProjects/Testing/testing1.py", line 41, in 
clicktheshit
    pyautogui.click(chords[0], chords[1])
TypeError: 'NoneType' object is not subscriptable

由于我的脚本对每个像素的搜索速度很慢,我想通过删除一些它所查看的无用像素(不在游戏区域中的像素)来加快它的速度,但使用

pxlss = pxls[60:400] 

不起作用,我不知道问题所在,因为它可以在不尝试删除无用的东西的情况下工作,只是速度很慢

import pyautogui
import time
from PIL import Image
import mss
import mss.tools
import cv2
import numpy as np
from PIL import ImageGrab
import colorsys

time.sleep(2)

def shootfunc(xc, yc):
    pyautogui.click(xc, yc)

gameregion = [71, 378, 328, 530]

def findpixels(pxls):
    pxlss = pxls[60:400]
    for row, pxl in enumerate(pxlss):
        for col, pxll in enumerate(pxl):
            if col >= 536 and col <= 808 and row <= 515 and row >= 371 and pxll == (102, 102, 102):
                foundpxl = pxll
                print(str(col) + " , " + str(row))
                return [col, row]
                break


def clicktheshit():
    with mss.mss() as sct:
        region = {'top': 0, 'left': 0, 'width': 1920, 'height': 1080}
        imgg = sct.grab(region)
        pxls = imgg.pixels
        chords = findpixels(pxls)
        pyautogui.click(chords[0], chords[1])

xx = 0
while xx <= 3000:
        clicktheshit()
        xx = xx + 1
        time.sleep(.01)
        clicktheshit()

标签: pythonindexing

解决方案


阅读错误消息和回溯应该会给您第一个提示:

File "C:/Users/yaahy/PycharmProjects/Testing/testing1.py", line 41, in clicktheshit
pyautogui.click(chords[0], chords[1])
TypeError: 'NoneType' object is not subscriptable

这意味着在这个确切的行中,chordsNone对象 - 当然不能被索引 - 而不是[col, row]您期望的列表。

现在为什么你得到这个None而不是预期的列表很简单:你的findpixels函数只有在它真正找到匹配时才返回这个列表 - 否则,函数最终没有明确的return声明,所以它隐含地返回None

IOW,您的问题与“仅迭代数组的特定部分的正确方法”无关……与不知道如何调试程序有很大关系。


推荐阅读