【问题标题】:NoneType object is not iterableNoneType 对象不可迭代
【发布时间】:2017-03-13 00:42:56
【问题描述】:

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

问题:我还在学习 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 (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

【问题讨论】:

  • 听起来像 pyautogui.locateOnScreen() 返回了 None。错误的完整回溯是什么?
  • 抱歉,我已将其添加到主帖中。这是我发布的第一个关于 python 的问题,所以我不确定你是否需要这一切来帮助 :-)
  • 是的,pyautogui.locateOnScreen() 返回了None,所以for ... in positions 失败,因为您不能循环遍历None。这意味着什么也没找到。
  • 啊,更改为 locateAllOnScreen 消除了错误,但随后什么也没有返回 :-( 所以要么我的位置线有问题,要么我的价值线有问题,应该把所有结果在一起。

标签: python python-3.x


【解决方案1】:

您需要通过 positions 添加检查 None 之前的迭代

#! 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)

【讨论】:

    猜你喜欢
    • 2016-02-08
    • 2020-05-06
    • 2013-12-01
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多