Search code examples
pythonmacoscolorsmousepyautogui

How to use PyAutoGUI to detect RGB values


I'm trying to build a small bot that clicks only certain colours. I believe pyautogui.displayMousePosition() should display the position of my mouse as well as the RGB values of the pixel the mouse is on. Instead, I'm only seeing the positional values (seen in the screenshot). Could this be an issue with MacOS?

No RGB values being displayed on python console - screenshot

Would also love to know if there's an alternate way I can go about this.


Solution

  • displayMousePosition() is the wrong function to be using for pretty much anything besides validating that the library is functioning correctly. It doesn't return any values, all it does is print information to console. I'd strongly suggest browsing pyautogui's documentation to find out more about the functionality the library provides.

    Assuming you know the screen x and y coordinates you are wanting to get the color of you'll want to take a screenshot of the screen and inspect the color values at the appropriate location.

    im = pyautogui.screenshot()
    px = im.getpixel((x, y))
    

    There is a wrapper that lets you get pixel information from a coordinate pair that you can use as well.

    px = pyautogui.pixel((x, y))