Search code examples
pythonpyautogui

How to click several image at random place in sequence from 1 to 5 using pyautogui


How to use PyAutoGui LocateOnScreen() to click on an image placed randomly on the screen? but it have to click the image in order from 1 to 5.


Solution

  • Assuming that the images you have to click appear randomly anywhere on the screen, but the images are not random, all you would have to do is organize the code.

    (just so you know I like to import 'pyautogui' as 'pe')

    for example:

    import pyautogui as pe
    import time
    
    image_1 = pe.locateCenterOnScreen('first_image_example')
    image_2 = pe.locateCenterOnScreen('second_image_example')
    image_3 = pe.locateCenterOnScreen('third_image_example')
    image_4 = pe.locateCenterOnScreen('fourth_image_example')
    image_5 = pe.locateCenterOnScreen('fifth_image_example')
    
    waitingloop = 1
    
    while waitingloop == 1:
        if image_1 == None:
            time.sleep(0.5)
        else:
            time.sleep(0.5)
            pe.click(image_1)
            break
    
    time.sleep(0.1)
    
    while waitingloop == 1:
        if image_2 == None:
            time.sleep(0.5)
        else:
            time.sleep(0.5)
            pe.click(image_1)
            break
    
    time.sleep(0.1)
    
    while waitingloop == 1:
        if image_3 == None:
            time.sleep(0.5)
        else:
            time.sleep(0.5)
            pe.click(image_3)
            break
    
    time.sleep(0.1)
    
    while waitingloop == 1:
        if image_4 == None:
            time.sleep(0.5)
        else: 
            time.sleep(0.5)
            pe.click(image_4)
            break
    
    time.sleep(0.1)
    
    while waitingloop == 1:
        if image_5 == None:
            time.sleep(0.5)
        else:
            time.sleep(0.5)
            pe.click(image_5)
            break
    

    This is a very easy way to do it, probably not the most efficient (since we have lots of lines of code), so if you want you can try to experiment with this.

    So, to break this down, as you can see I first defined a 'waitingloop = 1', which we will use to create a loop that will run forever, until the process is completed correctly... So for example in the first loop (for image_1), it says that everytime the 'locateCenterOnScreen()' function returns 'None' (a.k.a. didn't find the image) it will rerun the command again, until it finds the image, and once it finds it, it will click it and after that the loop breaks, once the loop break it waits a little bit (time.sleep) and then it starts up a new loop for 'image_2' and it repeats the same process until all 5 images have been clicked.

    This way all of your images will be clicked in other from 1 to 5 one at a time.

    Hope I was able to help you. Also try to be very detailed when asking something.