• POTD: Getting the pixels from tkinter

    From Stefan Ram@21:1/5 to All on Mon Sep 9 16:36:31 2024
    It's pretty much impossible to grab the color of pixels from
    tkinter using just the standard libraries. But seriously,
    who wants to mess around with extension libraries, right?

    Here's a thought that might actually let you read the color of a
    pixel from the tkinter GUI using only Python's standard libraries!
    The trick is to split the work: I'll show you how to do it on
    Windows, and then you can whip up the equivalent code for Linux!

    The following POTD (Program of the Day) illustrates how to read a
    pixel from the screen using only standard Python on Windows. You can
    set up any tkinter interface you want and then use this technique
    to pull the color of individual pixels from that interface!

    import ctypes

    # Constants for color retrieval
    GDI32 = ctypes.WinDLL('gdi32')
    USER32 = ctypes.WinDLL('user32')

    # Function to get the pixel color
    def get_pixel_color(x, y):
    # Get the device context for the entire screen
    hdc = USER32.GetDC(0)

    # Get the color of the pixel at (x, y)
    pixel = GDI32.GetPixel(hdc, x, y)

    # Release the device context
    USER32.ReleaseDC(0, hdc)

    # Extract RGB values
    blue = pixel & 0xFF
    green = (pixel >> 8) & 0xFF
    red = (pixel >> 16) & 0xFF

    return (red, green, blue)

    for col in range( 36 ):
    for row in range( 72 ):
    r, g, b = get_pixel_color( row, col )
    a = (r+g+b)/3
    print( end = '#' if a < 128 else ' ' )
    print()

    --- SoupGate-Win32 v1.05
    * Origin: fsxNet Usenet Gateway (21:1/5)