Question

Why does pyautogui throw an ImageNotFoundException instead of returning None?

I am trying to make image recognition program using pyautogui. I want the program to print "I can see it!" when it can see a particular image and "Nope nothing there" when it can't.

I'm testing for this by using pyautogui.locateOnScreen. If the call returns anything but None, I print the first message. Otherwise, I print the second.

However, my code is giving me an ImageNotFoundException instead of printing in the second case. Why is this happening?

import pyautogui

while True:
    if pyautogui.locateOnScreen('Dassault Falcon 7X.png', confidence=0.8, minSearchTime=5) is not None:
        print("I can see it!")
        time.sleep(0.5)
    else:
        print("Nope nothing there")
 2  45  2
1 Jan 1970

Solution

 2

From the pyautogui docs:

NOTE: As of version 0.9.41, if the locate functions can’t find the provided image, they’ll raise ImageNotFoundException instead of returning None.

Your program assumes pre-0.9.41 behavior. To update it for the most recent version, replace your if-else blocks with try-except:

from pyautogui import locateOnScreen, ImageNotFoundException

while True:
    try:
        pyautogui.locateOnScreen('Dassault Falcon 7X.png')
        print("I can see it!")
        time.sleep(0.5)
    except ImageNotFoundException:
        print("Nope nothing there")
2024-07-21
Andrew Yim