【问题标题】:Named colors in tkintertkinter 中的命名颜色
【发布时间】:2016-11-27 03:46:12
【问题描述】:

如何在 tkinter 中获取所有命名颜色的列表?我需要随机选择颜色并将其名称打印给用户。

我在这里找到了所有颜色的列表:Colour chart for Tkinter and Tix Using Python 我宁愿从库中获取列表,也不愿在我的程序中对其进行硬编码。

【问题讨论】:

  • 制作一个颜色列表并按照您想要的方式使用它们。就这么简单。
  • “我宁愿从库中获取列表,也不愿在我的程序中硬编码它。” - 在您的计算机某处创建一个包含所有这些颜色的文件,然后调用它。
  • 在 linux/debian 的情况下,文件 /etc/X11/rgb.txt 有类似“255 250 250 snow”的行。您的程序可以从该文件(或它的副本)中选择颜色。
  • 你可以发表你的评论作为答案,你会得到我的+1,因为这完全满足了懒惰。 @J.J.哈卡拉
  • 我最终创建了一个文件“racecolors.py”,它可以返回颜色名称列表,正如 Parviz 建议的那样。我现在明白 tkinter 是“唯一”本机 GUI 的接口,因此并非所有功能都可以通过 python 访问。

标签: python colors tkinter


【解决方案1】:

在 linux (debian) 的情况下,有一个文件 /etc/X11/rgb.txt 包含类似

的行
255 250 250             snow

并且应该易于解析。您的程序可以从该文件(或其副本)读取颜色定义到一个列表,然后从该列表中选择一种随机颜色。

【讨论】:

  • 在我的电脑上文件位于 /opt/X11/share/X11 感谢您的建议
【解决方案2】:

不一样但我写了一个可能有帮助的函数:

import numpy as np
import matplotlib.colors as mcolors

def get_random_colors(n, palette):
    """
    :param n: numbers of desired colors
    :param palette: similar palette color to choose
    :return: random_color_list
    """
    colors = mcolors.CSS4_COLORS  
    # Sort colors by hue, saturation, value and name.
    by_hsv = sorted((tuple(mcolors.rgb_to_hsv(mcolors.to_rgb(color))), 
    name) for name, color in colors.items())
    names = [name for hsv, name in by_hsv]
    if palette == 'black_white':
        color_list = names[0:13]
        max_colors = color_list.__len__()
    elif palette == 'reds_yellow':
        color_list = names[14:63]
        max_colors = color_list.__len__()
    elif palette == 'greens':
        color_list = names[64:84]
        max_colors = color_list.__len__()
    elif palette == 'blues':
        color_list = names[85:124]
        max_colors = color_list.__len__()
    elif palette == 'purple_pink':
        color_list = names[124:-1]
        max_colors = color_list.__len__()
    else:
        color_list = names
        max_colors = color_list.__len__()
    # check n and max colors
    if n > max_colors:
        print('max number of colors exceeded, please choose another palette')
        random_colors = None
    else:
        random_index = np.random.choice(range(color_list.__len__()), n, replace=False)
        random_colors = []
    for ii in random_index:
        random_colors.append(color_list[ii])

return random_colors

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 2017-06-13
    • 2018-07-21
    • 1970-01-01
    • 2017-10-05
    • 2020-11-10
    • 2018-06-10
    相关资源
    最近更新 更多