2

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.

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

#! 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
martineau
  • 119,623
  • 25
  • 170
  • 301
Brandon
  • 465
  • 3
  • 10
  • 19
  • 2
    Sounds like `pyautogui.locateOnScreen()` returned `None`. What is the *full* traceback of the error? – Martijn Pieters Mar 13 '17 at 00:44
  • Sorry I added it to the main post. This was the first question I ever posted about python so I wasnt sure if you needed it all to help :-) – Brandon Mar 13 '17 at 00:46
  • 1
    Yup, `pyautogui.locateOnScreen()` returned `None`, so `for ... in positions` fails as you can't loop over `None`. It means nothing was found. – Martijn Pieters Mar 13 '17 at 00:47
  • Ahh, changing to locateAllOnScreen gets rid of the error but then returns nothing :-( So either there is an issue with my positions line, or an issue with my value line that is supposed to put all of the results together. – Brandon Mar 13 '17 at 00:53
  • I guess I shall need to open another post to find out if my code to look through the digits folder is correct – Brandon Mar 13 '17 at 00:54
  • 1
    Possible duplicate of [TypeError: 'NoneType' object is not iterable in Python](http://stackoverflow.com/questions/3887381/typeerror-nonetype-object-is-not-iterable-in-python) – Kevin J. Chase Mar 13 '17 at 02:48

1 Answers1

8

You need to add check for None prior iteration through your 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)
cur4so
  • 1,750
  • 4
  • 20
  • 28