![]() |
PyautoGUI- How to use If - Else with pyautogui.locateCenterOnScreen - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: PyautoGUI- How to use If - Else with pyautogui.locateCenterOnScreen (/thread-35160.html) |
PyautoGUI- How to use If - Else with pyautogui.locateCenterOnScreen - Tiel - Oct-05-2021 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 objectInstead 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.
RE: PyautoGUI- How to use If - Else with pyautogui.locateCenterOnScreen - DeaD_EyE - Oct-05-2021 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}") RE: PyautoGUI- How to use If - Else with pyautogui.locateCenterOnScreen - Tiel - Oct-05-2021 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. RE: PyautoGUI- How to use If - Else with pyautogui.locateCenterOnScreen - DeaD_EyE - Jun-27-2022 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}") |