How to wait for the specific image to appear on screen using pyautogui?

Question:

I have one application which I am able to automate using the pyautogui module. I am keeping the reference image in the script directory, and after some sleep time, I am able to complete it. In some builds, the specific image takes a while to appear. After which my script throws attribute not found error.

I need to know how to control pyautogui to wait until the image appears on-screen and, after that, proceed for the next execution.

I have searched many stack overflow questions where I found wait_until() in the pywinauto module where a script waits for specific window. In the same way, do we have anything for pyautogui to wait for a specific image to appear on-screen?

Python version used: 3.6.

Asked By: user3664681

||

Answers:

This will wait until it finds the image:

icon_to_click = "Recycle Bin"

r = None
while r is None:
    r = pyautogui.locateOnScreen('rb.png', grayscale = True)
print icon_to_click + ' now loaded'
Answered By: feltersnach

In newer version of Python (3.6), locateOnScreen() no longer returns None if it can’t find an image. It would raise an exception instead. After struggling for 10 mins, I found the solution below to be working:

r = None
while r is None:
    try:
        print(pyautogui.locateOnScreen("rb.png"))
        break
    except Exception as e:
        r = None
Answered By: user10953441

It did not work for me (probably I did something wrong) but I could fix this with a while loop and locatedOnscreen where I then use two if statements and break where we see the picture.

while 1:
    sleep(1)
    
    black_market = pt.locateOnScreen(
        "imgs/black_market.png", grayscale=False,
        region=(709,646,161,141), confidence=0.8)
    if black_market is not None:
        print("I see black market")
        break
    
    black_market = pt.locateOnScreen(
        "imgs/black_market.png", grayscale=False,
        region=(709,646,161,141), confidence=0.8)
    if black_market is None:
        print("I do not see black market")  
Answered By: Mikey Goby