2

I have a question about tkColorChooser. I am working on a GUI for plotting functions and a user of the program has to pick the color of the function they want to plot. I would like to test whether the color they pick is a valid tkColorChooser color.

I was thinking about doing tests such as len(colorString) == 7 (or 4) or colorString.startswith('#'), but I would still have to do testing for the color names such as 'black' and 'green' and all other colors available... It all seems like a lot of work, so I was wondering if there is an easier way to do that?

I am interested in a test such as

string = 'black'
Is string a valid color ?
return True

string = 'blac'
Is string a valid color?
return False

Cheers!

4

2 回答 2

3

您可以在根窗口上调用该方法winfo_rgb,给它一个代表颜色的字符串。如果颜色有效,您将获得红色、绿色和蓝色分量。如果它无效,您将获得异常。

http://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.winfo_rgb-method

于 2013-05-13T12:26:35.457 回答
0

您是否让用户输入颜色名称?如果是这样,为什么不让用户直接从 tkColorChooser 中选择颜色呢?这样,用户选择的任何颜色都是定义上的有效颜色。

这个例子来自Jan Bodnar (zetcode.com)

import Tkinter as tk
class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)   
        self.parent = parent        
        self.initUI()

    def initUI(self):
        self.parent.title("Color chooser")      
        self.pack(fill=tk.BOTH, expand=1)

        self.btn = tk.Button(self, text="Choose Color", command=self.onChoose)
        self.btn.place(x=30, y=30)

        self.frame = tk.Frame(self, border=1, 
                              relief=tk.SUNKEN, width=100, height=100)
        self.frame.place(x=160, y=30)

    def onChoose(self):
        rgb, hx = tkColorChooser.askcolor()
        print(rgb)
        print(hx)
        self.frame.config(bg=hx)

root = tk.Tk()
ex = Example(root)
root.geometry("300x150+300+300")
root.mainloop() 
于 2013-05-13T12:07:00.780 回答