Python NoneType 对象不可迭代

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42755006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 22:07:07  来源:igfitidea点击:

NoneType object is not iterable

pythonpython-3.x

提问by Brandon

I am getting a 'NoneType' object is not iterable TypeError in the code below. The code below is ment to use pyautogui to scroll through 10 images in the digits folder (named 0 through 9, named with the # in the image) and when ever it finds one, report the value of x along with the number it found. The dictionary is then sorted by x values to read the number found in the image.

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

Question:I am still learning Python and this TypeError has me stomped, how can I correct this?

问题:我仍在学习 Python 并且这个 TypeError 使我跺脚,我该如何纠正?

#! 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 of the error:

错误追溯:

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

回答by cur4so

You need to add check for Noneprior iteration through your positions

您需要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)