获取当前 tk 调色板的颜色代码

问题描述

在 tkinter 中,是否可以获取当前使用的调色板的颜色,以便我可以使用它们,例如在画布上绘制矩形时?

A

我知道我可以使用例如'bisque' 作为颜色名称,但是 documentation 表示包含诸如“activeBackground”、“highlightColor”等条目的数据库。我想知道如何将这些用作画布项目的颜色,或者只是如何在运行时获取它们的 rgb 值。

解决方法

您可以使用 root.option_get(name,'.') 获取小部件的默认颜色:

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','.'))

给予

#ffe4c4
#e6ceb1
黑色
黑色

如果您需要特定小部件类的颜色,请将 '.' 替换为类名。如评论中所述,如果您需要颜色的 RGB 值,您可以使用 root.winfo_rgb(color) 其中 color 是十六进制格式或 tkinter 预定义颜色之一,例如黑色,...(您例如可以找到一个列表 here)。

但是,在我的计算机上(我使用的是 Linux,我不知道在所有平台上的行为是否相同)它仅在将配色方案设置为 bisque 后才有效,对于默认配色方案,它始终返回 {{ 1}}。