Python Forum

Full Version: PyautoGUI- How to use If - Else with pyautogui.locateCenterOnScreen
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Essentially I want my Python script to perform this...

     x = True
     if x  == True:
         print('Congratulations, you won!')
     else:
         print('I'm sorry but you lost.')
with this...

     a, b = pyautogui.locateCenterOnScreen('~/home/file_01.png', region=(1065,250,385,700), confidence=0.9)

In other words, how can I have my script check to see if PyautoGUI has successfully located the center of ~/home/file_01.png?

See, about 95% of the time the following works correctly....

     a, b = pyautogui.locateCenterOnScreen('~/home/file_01.png', region=(1065,250,385,700), confidence=0.9)
But about 5% of the time ~/home/file_01.png does not exist. In those cases my script stops and throws off the following error message...

     TypeError: cannot unpack non-iterable NoneType object
Instead of having my script stops in cases when ~/home/file_01.png does not exist I would prefer that my script skip that instance. In other words, instead of stopping I want my script to ignore cases when ~/home/file_01.png does not exist.
The cause is that pyautogui.locateCenterOnScreen return a Point object or None if the image was not found on screen.

You already got the right Exception, which you can catch.
import pyautogui


try:
    x, y = pyautogui.locateCenterOnScreen("your_image.png")
except TypeError:
    print("Could not locate the image")
    # this is only executed, if a TypeError was caught
    # for example you can exit here with sys.exit(1)
    # or with raise SystemExit("Sorry, image not found")
else:
    # this block is executed, if no exception happened
    print(f"All fine, got the coordinates: {x} | {y}")
Thank you very much!

Your solution worked perfectly on my first two tries.

First I ran your solution without the image visible and second, of course, I ran it with the image visible.
Here is an additional naive solution without using Exceptions:
import pyautogui
 
coords = pyautogui.locateCenterOnScreen("your_image.png")

# coords is None -> no result
if coords is None:
    print("Could not locate the image")
else:
    x, y = coords  # tuple unpacking
    print(f"All fine, got the coordinates: {x} | {y}")