Changing the background color of a tkinter window using colorchooser module


Tkinter offers a wide variety of modules and class libraries using which we can create fully functional applications. Tkinter also provides widgets to build the components and skeletons of an application. The colorchooser module in tkinter is one of them which provides a huge set of colors so that users can pick and set the background color of widgets based on their preference.

To add the colorchooser functionality in your application, you have to first import this module in your program using "from tkinter import colorchooser". Next, create a variable to display a color palette using colorchooser.askuser().

Since all the colors in the palette are indexed and separated by their index number, you can specify the tuple from where the color should start. Finally, enclose the background color with the given variable to change the color of any widget.

Example

Let us understand this with an example.

# Import the library
from tkinter import *
from tkinter import colorchooser

# Create an instance of window
win=Tk()

# Set the geometry of the window
win.geometry("700x350")

# Create a label widget
label=Label(win, text="This is a new Label text", font=('Arial 17 bold'))
label.place(relx=0.5, rely=0.2, anchor = CENTER)

# Call the function to display the color palette
color=colorchooser.askcolor()

# Initialize the color range by picking up the first color
colorname=color[1]

# Configure the background color
win.configure(background=colorname)

win.mainloop()

Output

Running the above code will display a window with a Label widget and a color palette asking the user to choose a color.

The selected color will reflect in the background color of the window.

Updated on: 28-Dec-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements