简体   繁体   中英

Getting color codes of the current tk palette

In tkinter, is it possible to get the colours of the currently used palette, so that I can use them eg when drawing a rectangle on the canvas?

import tkinter as tk
root = tk.Tk()
root.tk_bisque() # change the palette to bisque
canvas = tk.Canvas(root, width=500, height=500)
canvas.create_rectangle(10, 10, 100, 100, fill='???') # What to enter here?

I know I can use eg 'bisque' as a colour name, however the documentation speaks of a database containing entries like 'activeBackground', 'highlightColor', etcetera. I want to know how to use those as colours for my canvas items, or alternatively simply how to get their rgb values at runtime.

You can use root.option_get(name, '.') to get the default colors of the widget:

import tkinter as tk
root = tk.Tk()
root.tk_bisque() # change the palette to bisque
print(root.option_get('background', '.'))
print(root.option_get('activeBackground', '.'))
print(root.option_get('foreground', '.'))
print(root.option_get('highlightColor', '.'))

gives

#ffe4c4
#e6ceb1
black
black

If you need the color for a specific widget class, replace '.' by the class name. As mentioned in the comments, if you need the RGB value of the color, you can use root.winfo_rgb(color) where color is either in HEX format or one of tkinter predefined colors such as black, ... (you can find a list here for instance).

However, on my computer (I am using Linux and I don't know if the behavior is the same on all platforms) it only works after setting the color scheme to bisque, for the default color scheme it always return '' .

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