Search code examples
pythonpyautogui

PyAutoGui and loops


I just want my whole code Below to be repeated to which value I set means if I set 10 so my code runs 10 times without asking any permission or input from me. The only way to stop is to wait or manually stop If anyone knows please solve my problem.. Full code to be repeated not some lines

from pyclick import HumanClicker import pyautogui import math import time import random import os import sys from time import sleep hc = HumanClicker() pyautogui.FAILSAFE = True

sleep(4) coords = pyautogui.locateCenterOnScreen('calc.png', confidence=0.6)

if coords is None: print("image not found")

else: hc.move((coords), 2) hc.click()

coords1 = pyautogui.locateOnScreen('calc1.png') if coords1 is None: print('Image not found on the screen!')

else: hc.move((coords1), 2) hc.click()

coords2 = pyautogui.locateOnScreen('calc2.png') if coords2 is None: print('Image not found on the screen!')

else: hc.move((coords2), 2) hc.click()

coords3 = pyautogui.locateOnScreen('calc4.png', confidence=0.6) if coords3 is None: print('Image not found on the screen!')

else: hc.move((coords3), 0.5) hc.click()


Solution

  • from pyclick import HumanClicker
    import pyautogui
    import math
    import time
    import random
    import os
    import sys
    from time import sleep
    hc = HumanClicker()
    pyautogui.FAILSAFE = True
    
    sleep(4)
    
    coords = []
    NUMBER_OF_IMAGES = 4 # change this to your needs
    for i in range(NUMBER_OF_IMAGES):
        coords[i] = pyautogui.locateOnScreen(
                                             ("calc" if i == 0 else "calc" + str(i))+".png",
                                             confidence = 0.6
                                            )
        if coords[i] is None:
            print("Image not found on the screen!")
        else:
            hc.move((coords[i]), 2)
            hc.click()
    

    This just loops through all of the images, getting and (if coordinates are not None) clicking them. All you have to do is set the number of images, NUMBER_OF_IMAGES.

    Notes:

    1. The confidence is 0.6
    2. The math, time, random, os, sys, and time modules are unnecessary. To use time.sleep, use pyautogui.sleep (it was made so that you don't have to import time)
    3. The sleep(4) statement does not seem helpful.

    If this is part of a bigger project that requires those modules and sleep(4), you should keep them. Otherwise, try to remove unnecessary code from your Python program.