PyAutoGUI "PixelMatchesColor" always TRUE

Advertisements

I’m trying to check a pixel on my screen using pyautogui "PixelMatchesColor" function, but it always runs the code even if the pixel color is not correct.

Here’s my code:

def myFunction():
    im = pyautogui.screenshot()
    color = im.getpixel((1992, 1435))
    print(color)
    try:
        pyautogui.pixelMatchesColor(1992, 1435, (85, 214, 142))
        print("Color found")
    except:
        print("Color not found")

Output:

(16, 52, 154)
Color found

Do you know where I’m making a mistake?

>Solution :

As seen in https://pyautogui.readthedocs.io/en/latest/screenshot.html#pixel-matching, pixelMatchesColor returns a boolean value True or False to indicate whether the color matches.

To branch on a boolean value, use an if statement. A try statement is for catching exceptions, which is not relevant here.

if pyautogui.pixelMatchesColor(1992, 1435, (85, 214, 142)):
    print("Color found")
else:
    print("Color not found")

Leave a ReplyCancel reply