NoneType对象不可迭代

时间:2017-03-13 00:42:56

标签: python python-3.x

我在下面的代码中得到一个'NoneType'对象不能迭代TypeError。下面的代码是使用pyautogui滚动数字文件夹中的10个图像(名称为0到9,用图像中的#命名),当它找到一个时,报告x的值以及它找到的数字。然后按x值对字典进行排序,以读取图像中找到的数字。

问题:我还在学习Python,这个TypeError让我st脚,我怎么能纠正这个?

#! python3
import sys
import pyautogui

# locate Power
found = dict()
for digit in range(10):
    positions = pyautogui.locateOnScreen('digits/{}.png'.format(digit),
                                         region=(888, 920, 150, 40), grayscale=True)
    for x, _, _, _ in positions:
        found[x] = str(digit)
cols = sorted(found)
value = ''.join(found[col] for col in cols)
print(value)

追踪错误:

Traceback (most recent call last):
  File "C:\Users\test\python3.6\HC\power.py", line 10, in <module>
    for x, _, _, _ in positions:
TypeError: 'NoneType' object is not iterable

1 个答案:

答案 0 :(得分:6)

您需要在None

之前添加positions之前迭代的检查
#! python3
import sys
import pyautogui 

# locate Power
found = dict()
for digit in range(10):
    positions = pyautogui.locateOnScreen('digits/{}.png'.format(digit), region=(888, 920, 150, 40), grayscale=True)
    if positions is not None: 
        for x, _, _, _ in positions:
            found[x] = str(digit)
cols = sorted(found)
value = ''.join(found[col] for col in cols)
print(value)