Tkinter Color Chooser

This section covers the color chooser module in Tkinter.

Tkinter is full of mini libraries that offer new and interesting features, improving the overall look and feel of your Python GUI. One of these many Tkinter Libraries is the Color Chooser.

You can import the askcolor function from the Color Chooser library using the following code.

from tkinter.colorchooser import askcolor  

The syntax for the askcolor function is as follows. All parameters on this function or optional. You can assign it a default color and a title, but you can also leave both of these out.

result = askcolor(title = "Tkinter Color Chooser")

The look of this Color Chooser can vary from operating system to operating system, but the general purpose and functionality remains the same.

Tkinter Color Chooser

Color Chooser Example

Below is a standard example of the askcolor function, without the supporting tkinter window.

Any color you pick will return a tuple as it’s value. There are two values contained in this tuple. The first is a RGB representation and the second is a hexadecimal value. We’ll be needing the hexadecimal value for tkinter.

result = askcolor(title = "Tkinter Color Chooser")

print(result)
print(result[0])
print(result[1])

We picked a random color using the code above. See it’s output below.

((92.359375, 116.453125, 228.890625), '#5c74e4')
(92.359375, 116.453125, 228.890625)
#5c74e4

Extra Tkinter Example

Here’s an extra example of the use of the Color Chooser’s askcolor function. This is the kind of example you’ll see in real life, where the user selects a color, and the font color on the GUI changes accordingly.

Tkinter non-color window
from tkinter.colorchooser import askcolor                  

def callback():
    result = askcolor(title = "Tkinter Color Chooser")
    label.configure(fg = result[1])
    print(result[1])
    
root = tk.Tk()
tk.Button(root, text='Choose Color',command=callback).pack(pady=20)

label = tk.Label(root, text = "Color", fg = "black")
label.pack()

root.geometry('180x160')
tk.mainloop()

We’ve run the function, and picked the color blue from the color palette. You can now see that the color of the text in the label has been changed.

Tkinter color window

This marks the end of the Tkinter Color Chooser Article. Suggestions or contributions for CodersLegacy are more than welcome. Any questions can be directed to the comments section below.

To see other tkinter related tit bits, head over to the Python problem solving page and scroll down to the Tkinter section.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments