简体   繁体   中英

How can I get HEX or RGB color code of the window background color?

I'd like to find the window background color in HEX format. Looking for a solution that works on all platforms... Windows/Linux/Mac...

The following code print (self.cget('bg')) just prints SystemButtonFace but I'd like to get the actual HEX format. The reason is that I need to use this color as a base to create a new slightly darker color shade.

The winfo_rgb method on all widgets will accept a color name and return the r, g, and b components as integers in the range of 0-65535 (16 bits). You can then convert those to hex using standard python string formatting.

Thanks to Bryan Oakley's answer wrote this method:

def get_widget_hex_color_by_known_name(w, knwon_system_color):
    """
    w is a tkinter widget i.e. tk.Button() or self
    knwon_system_color can be any known color name like white, green, SystemButtonFace
    """
    rgb = w.winfo_rgb(knwon_system_color)
    r,g,b=[x>>8 for x in rgb]
    return '#{:02x}{:02x}{:02x}'.format(r,g,b)

Note that self.cget('bg') returns something like SystemButtonFace on Windows, but on Linux it actually return the hex color code.

So I only need to call the function above if the self.cget('bg') call does not return a hex color code (string length 7 starting with #).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM