pyautogui throws me error message. How can I fix my code?

Question:

It gives me error message like below. How can I fix this?

Traceback (most recent call last):
  File "c:UsersjayjeotempCodeRunnerFile.py", line 3, in <module>
    x, y = pyautogui.locateCenterOnScreen('yellow.png', confidence=0.8)
TypeError: cannot unpack non-iterable NoneType object

I made a code as below. I think that if x.size == 0: is the problem.

import pyautogui

x, y = pyautogui.locateCenterOnScreen('yellow.png', confidence=0.8)
if x.size == 0:
    print("Not Detected")
    pyautogui.click(1280,720)
else:
    print("Detected")
    pyautogui.click(x, y)

When I do print(x), I get the same error message.

Asked By: Jay Jeong

||

Answers:

This was changed in version 0.9.41. After that point, if the window is not found, it raises an exception. Before that point, it returns None. So, you need:

pt = pyautogui.locateCenterOnScreen('yellow.png', confidence=0.8)
if not pt:
    print("Not Detected")
    pyautogui.click(1280,720)
else:
    x, y = pt
    print("Detected")
    pyautogui.click(x, y)

If you upgrade, you will have to add exception handling for this case.

Answered By: Tim Roberts
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.