Title: Display a color picker in Python and tkinter
The program uses the following code to create its button.
# Make a button.
self.color_button = tk.Button(self.window, text='Pick Color',
bg='light green', command=self.choose_color)
self.color_button.pack(side=tk.TOP, padx=10, pady=10)
This code simply creates the button. It sets the button's background color to light green and sets its command property to the choose_color method. (Note that I have seen posts saying the bg property may not work correctly on the Mac. Some people have gotten better results with the highlightbackground property, but that didn't work for me in Windows.)
When you click the button, the following code executes.
def choose_color(self):
current_color = self.color_button.cget('bg')
color = colorchooser.askcolor(title='Choose Color',
initialcolor=current_color)
if color[1] is not None:
self.color_button.config(bg=color[1])
This code first gets the button's current background color. This will be a string like light green or #ff80ff.
The program then calls colorchooser.askcolor to display the color chooser dialog. That method returns a tuple holding the selected color in two forms. The first form is a tuple giving the color's red, green, and blue components. The second form is a hexadecimal text string. The following text shows a sample.
((255, 255, 128), '#ffff80')
If you cancel the dialog, the askcolor method returns the tuple (None, None). The program checks the returned tuple and, of the second value is not None, the code configures the button to use that value as its background color.
Download the example to see all of the details.
|