Back to: Python Programming
0
The tkinter.colorchooser module in Python provides an interface to the native colour picker dialog of the operating system. It allows users to select a colour which is then returned to the application as both a hexadecimal string and an RGB tuple.
Key Features
askcolor()function: This is the primary function used to display the dialog box and return the selected color information.- Returns a tuple: The function returns a tuple containing the RGB values and the hexadecimal string of the selected color, e.g.,
((255, 0, 0), '#ff0000')for red. - Cross-Platform: The dialog box presented is typically the native OS color picker, ensuring a familiar user experience across Windows, macOS, and Linux (though Linux may use a Tkinter-drawn dialog).
- Dynamic Updates: The returned hexadecimal value can be immediately used with the
configorconfiguremethod to change the color of widgets like labels, buttons, or the background of the main window.
from tkinter import *
from tkinter import colorchooser # This is a submodule so must be chosen separately
def selectColour():
color = colorchooser.askcolor()
colorHex = color[1]
window.config(bg=colorHex)
window = Tk()
window.geometry("420x420")
button = Button(text='Click here for Colour Selection',command=selectColour)
button.pack()
window.mainloop()

A more sophisticated example will complete this short module
from tkinter import *
from tkinter import colorchooser
def pick_color():
# Opens the native color selection dialog
color_code = colorchooser.askcolor(title="Choose Colour")
# color_code is a tuple: ((r, g, b), hexadecimal_string)
# If the user cancels, it returns (None, None)
if color_code[1]: # Check if a colour was selected
print(f"RGB values: {color_code[0]}")
print(f"Hex code: {color_code[1]}")
# You can use the hex code to configure widget colours
my_label.config(fg=color_code[1])
root.config(bg=color_code[1]) # Example: change window background
# Main Tkinter window
root = Tk()
root.title("Colour Chooser Example")
# Label to display text and change colour
my_label = Label(root, text="Select a colour for this text!", font=("Helvetica", 16))
my_label.pack(pady=20)
# Button to trigger the color chooser dialog
color_button = Button(root, text="Pick a Colour", command=pick_color)
color_button.pack(pady=10)
# Start the Tkinter main loop
root.mainloop()
