Reputation: 371
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!
Upvotes: 2
Views: 1006
Reputation: 880279
Are you having the user type in a color name? If so, why not instead let the user pick the color directly from the tkColorChooser? That way, whatever color the user picks is a valid color by definition.
This example comes from 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()
Upvotes: 0
Reputation: 386210
You can call the method winfo_rgb
on the root window, giving it a string that represents a color. If the color is valid you'll get the red, green and blue components. If it is invalid you will get an exception.
See http://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.winfo_rgb-method
Upvotes: 3