Search code examples
pythontkintercolors

How do I get custom colors using color chooser from tkinter


In the askcolor function of class Chooser in the pop up you can add color to a custom colors list. I was wondering if I can somehow get the values of those colors, but I could not find a way how to do it.

Code for the pop up:

from tkinter import colorchooser
color_code = colorchooser.askcolor()

Pop up screen shot:

Pop Up askcolor


Solution

  • The function tkinter.colorchooser.askcolor() doesn't directly provide access to the custom colors list in its popup. The function's main role is to return the selected color.

    The closest you can get is keeping track of the colors by creating a list (custom_colors = []) and then every time color_code = colorchooser.askcolor() is called, .append to the list. E.g.:

    from tkinter import colorchooser, Tk, Button
    root = Tk()
    custom_colors = []
    
    def choose_color():
        color_code = colorchooser.askcolor()
        if color_code[1]:
            if color_code[1] not in custom_colors:
                custom_colors.append(color_code[1])
    
        print(custom_colors)
    
    
    choose_button = Button(root, text="Choose Color", command=choose_color)
    choose_button.pack(pady=20)
    
    root.mainloop()