How can I loop PyAutoGUI's locateCenterOnScreen until the image is found?

Question:

I’m running Python 3.8.10 on Lubuntu 20.04 LTS.

How can I modify:

a, b = pyautogui.locateCenterOnScreen('/home/image01.png', confidence=0.6, region=(25,500,1700,570))

so that it loops until image01.png is found?

See, in my script, the following works approximately 90% of the time for me:

a, b = pyautogui.locateCenterOnScreen('/home/image01.png', confidence=0.6, region=(25,500,1700,570))

But about 10% of the time it fails resulting in:

TypeError: 'NoneType' object is not iterable

Based on Why can't pyautogui locate my image although the code seems to be just fine? it seems like instead of running my code once, perhaps I should loop the following function until the image is detected.

I don’t know how to implement it, but once again based on Why can't pyautogui locate my image although the code seems to be just fine?
the following seems like it would be helpful…

def detect_image(path, duration=0):
    while True:
        image_location = pyautogui.locateCenterOnScreen(path)
        if image_location:
            pyautogui.click(image_location[0], image_location[1], duration=duration)
            break
Asked By: Tiel

||

Answers:

I had to do something similar not long ago.

First of all I imported ‘Pyautogui’ as ‘pe’ and also I imported time.

So this is what I did.

waitingloop = 1

I defined a waiting loop that is equal to one, and then using that I wrote

    while waitingloop == 1:
        if pe.locateCenterOnScreen('signinbox.png') == None:
            time.sleep(0.5)
        else:
            time.sleep(0.5)
            pe.typewrite(email)
            pe.hotkey('enter')
            break

So as you can see, with the ‘waitingloop’ this process will be running all the time, and then everytime IT FAILS to locate the image and returns ‘None’ it sleeps for 0.5 seconds and tries to do so again until it actually finds the image, then when it finds it as you can see it just does what I wanted it to do (in your case it would be ‘click’) and once it does that the loop breaks.

I hope this code can help you.

Answered By: winston1420

I know this question is about a year old, but the other answer is no longer relevant since locateCenterOnScreen() does not return None anymore, so this answer is for anyone who looked this up.

At the start of the program you must have this function.

pyautogui.useImageNotFoundException()

This code loops infinitely with a try-catch until locateCenterOnScreen no longer raises ImageNotFoundException.

while True:
    try:
        x, y = pyautogui.locateCenterOnScreen()
        break
    except pyautogui.ImageNotFoundException:
        pass
Answered By: aleksei plus plus
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.