Skip to content
Advertisement

Pyautogui TypeError: ‘NoneType’ object is not iterable

I’m trying to use locateCenterOnScreen() function of PyAutoGUI, however it raises :

Traceback (most recent call last):
  File "C:UserswindowsDesktopasd.py", line 3, in <module>
    buttonx, buttony = pyautogui.locateCenterOnScreen('who.jpg')
TypeError: 'NoneType' object is not iterable

My code is:

import pyautogui

buttonx, buttony = pyautogui.locateCenterOnScreen('who.jpg')
pyautogui.doubleClick(buttonx,buttony)

How can I fix this problem?

Advertisement

Answer

From the documentation of Pyautogui here, the method locateCenterOnScreen returns None when it can’t find the image on your screen.

Note that you are looking for 2 results from this method, but None is just one result (since the method normally returns two, this seems like bad design to me — it should raise an exception instead, or at least return a tuple with two None objects).

Look at the following example, which is basically what is happening to you:

>>> foo,bar = None
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not iterable

The simplest and most Pythonic way of addressing this in my opinion would be simply to try and catch it:

try:
    buttonx,buttony = pyautogui.locateCenterOnScreen('who.jpg')
except TypeError:
    """ Do something to handle the fact that the image was not found"""

EDIT: To answer your question raised in the comments, there seems to be a misunderstanding with how this library works, or what it finds on the screen. You give the library a representation of what it needs to find via some image. It works far better when that image is lossless, because then it’s an exact, pixel-by-pixel representation. The library then searches your computer screen for the actual thing represented by the image provided. It does not, as you raised concerns, find jpegs or pngs. It finds the actual rendered object. So, if you take a screen shot of the icon for your web browser on your desktop, it will find the actual icon from that screenshot and click on it, but only if it’s visible. If it’s behind other windows or something, it won’t find it. It doesn’t search the screen for the icon file, but the rendering of the icon itself. So, for instance, if you provided the actual .ico file to the library, it would not be able to find that icon if it was covered by another window, even though that icon is technically on your desktop, because it’s not currently rendered.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement