如何检测悬停Python的背景颜色?

6rqinv9w  于 2022-12-17  发布在  Python
关注(0)|答案(1)|浏览(147)

有谁知道,你是怎么用python检测你的光标所停留的颜色,然后把颜色返回给一个字符串的?

1l5u6lss

1l5u6lss1#

适用于Windows的解决方案:

def get_cursor_color():
    # Get the cursor position
    pt = ctypes.wintypes.POINT()
    ctypes.windll.user32.GetCursorPos(ctypes.byref(pt))

    # Get the color of the pixel at the cursor position
    hdc = ctypes.windll.user32.GetDC(None)
    color = ctypes.windll.gdi32.GetPixel(hdc, pt.x, pt.y)

    # Release the device context
    ctypes.windll.user32.ReleaseDC(None, hdc)

    # Return the color as a tuple of (R, G, B) values
    return (color & 0xff, (color >> 8) & 0xff, (color >> 16) & 0xff)

print(get_cursor_color())

Linux的解决方案:

def get_cursor_color():
    # Open a connection to the X server
    display = Xlib.display.Display()
    screen = display.screen()

    # Get the root window and the color map
    root_window = screen.root
    colormap = screen.default_colormap

    # Query the X server for the cursor position
    pointer = display.query_pointer(root_window)
    x, y = pointer.root_x, pointer.root_y

    # Get the pixel at the cursor position
    pixel = root_window.get_image(x, y, 1, 1, Xlib.X.ZPixmap, 0xffffffff).data[0]

    # Convert the pixel value to an (R, G, B) tuple
    return colormap.query_color(pixel)._data

print(get_cursor_color())

结果为RGB值

相关问题