Tkinter colorchooser askcolor() Method
The colorchooser module within the tkinter module has the askcolor() method, which opens the Color
dialog box in which we can easily select colors.
Tkinter colorchooser askcolor() Method Example#1
Use to open the Color
dialog.
from tkinter import *
from tkinter.colorchooser import *
def bgUpdade():
''' Change window background color '''
myColor = askcolor() # List Color Dialog
print(type(myColor),myColor) # Print the value passed back
root.config(bg=myColor[1]) # Set window background color
root = Tk()
root.title("apidemos.com")
root.geometry("360x240")
btn = Button(root,text="Select Color",command=bgUpdade)
btn.pack(pady=5)
root.mainloop()
Output:
When you click the Select Color button, you can see the Color
dialog box on the right below.
Clicking the OK
button in the figure on the right will give you the following results.
In line 6, the askcolor( ) method opens the Color
dialog, selects the color, and then clicks the OK button to return the value to myColor. line 8 prints the returned value to myColor using the Python Shell window, which returns the following data.
The data type of the above passed back values is a tuple, and there are two elements in this tuple. The element at index 0 is also a tuple, and this element contains three data, each of which is a color value of RGB. The element at index 1 is a 16-bit color string. We can use the color string to set the background color of the window.