Search code examples
python-3.xif-statementwhile-looppyautogui

Python automation with pyautogui if statements wont execute


#! python3
import pyautogui
import time 
pyautogui.screenshot('first.png') #take a SS of my entire screen
check = pyautogui.locateCenterOnScreen('first.png') # set the value of check to center of screen assuming it will be the same as the SS...it will
print(check) #(960, 540) is the center of my screen and is stored in check
while True: #inf loop
    pyautogui.screenshot('Test.png') #take a second Screenshot
    idleout = pyautogui.locateCenterOnScreen('Test.png') #set the value of idleout with the center of test.jpg
    print(idleout) #(960, 540) is the center suprised??
if idleout != check: #idleout != (960, 540) then this should happen
    pyautogui.press('space') #space is never pressed or any action taken ive even tried with print("hello")

what i want to happen is if the screen shot does not match what is currently on my screen it will do some action. im running on fumes here


Solution

  • I'm not sure if the formatting on SO is set up correctly (your comments are showing as keywords), but it looks like you have the if statement outside of your while True loop. If that's the case, it will never get executed (or checked).

    #! python3
    import pyautogui
    import time 
    pyautogui.screenshot('first.png')
    check = pyautogui.locateCenterOnScreen('first.png')
    print(check)
    while True:
        pyautogui.screenshot('Test.png')
        idleout = pyautogui.locateCenterOnScreen('Test.png')
        print(idleout)
        if idleout != check:
            pyautogui.press('space')