
Color picker or what ?

Post by Amina Delali, December 27th, 2022
Description
To create the color picker, using tkinter, you can use the function askcolor from the colorchooser module of tkinter.
The call of the askcolor function, will show the modal color choosing dialog window.
There are two scenarios after the windows shows up:
- The first one: the user select a color, then click on ok button. In that case, the function will return a tuple describing the chosen color. The tuple will have tow values: a tuple of ints corresponding to the rgb color code of the selected color. The second tuple will contain a string of the corresponding hexadecimal color code.
- The second one: the use click on the cancel button. In that case, the function will return a tuple of two None values. Assigning the None value as a color for a widget, will not affect its appearance.
In the following code, we will use the askcolor function to show the color picker, then we will assign the recuperated color value (the second value of the returned tuple), to the background color (bg property) of the main window of the application.
The function is called inside another function: color_picker, that will be the command property of the button, that will show the color picker dialog, when the user click on that button.
The Code
from tkinter import *
from tkinter import colorchooser
main_window=Tk()
main_window.title("This a Color Picker")
main_window.geometry('500x450+400+100')
main_window.configure(bg="#8800FF")
def color_picker():
color_code = colorchooser.askcolor(title ="Select a Color")
main_window.configure(bg=color_code[1])
button = Button(main_window, text = "Select a color",
bg="#f4FF00", bd=1,
command = color_picker)
button.pack(pady=20,padx=20, side=RIGHT, anchor=NW)
main_window.mainloop()
The Output

Something to say?
If you want to add something about this post, please feel free to do it by commenting below 🙂.