Changing the background color of a tkinter window using colorchooser module

Tkinter offers a wide variety of modules and class libraries for creating fully functional applications. The colorchooser module provides an interactive color palette that allows users to select colors for customizing their application's appearance, particularly useful for changing background colors of windows and widgets.

To use the colorchooser functionality, you need to import the module using from tkinter import colorchooser. The main function colorchooser.askcolor() opens a color selection dialog and returns a tuple containing both RGB values and the hex color code.

Understanding colorchooser.askcolor()

The askcolor() function returns a tuple with two elements:

  • color[0] − RGB tuple (red, green, blue values)
  • color[1] − Hex color string (e.g., "#FF5733")

Example: Interactive Background Color Changer

Here's a complete example that demonstrates changing a window's background color using colorchooser ?

# Import the required modules
from tkinter import *
from tkinter import colorchooser

# Create an instance of window
win = Tk()

# Set the geometry of the window
win.geometry("700x350")
win.title("Background Color Changer")

# Create a label widget
label = Label(win, text="Click the button to change background color", 
              font=('Arial', 17, 'bold'))
label.place(relx=0.5, rely=0.3, anchor=CENTER)

# Function to change background color
def change_color():
    # Call the function to display the color palette
    color = colorchooser.askcolor()
    
    # Check if user selected a color (not cancelled)
    if color[1]:
        # Get the hex color code
        colorname = color[1]
        # Configure the background color
        win.configure(background=colorname)

# Create a button to trigger color selection
button = Button(win, text="Choose Background Color", 
                command=change_color, font=('Arial', 12))
button.place(relx=0.5, rely=0.6, anchor=CENTER)

win.mainloop()

How It Works

When you run this code:

  1. A window appears with a label and button
  2. Clicking the button opens the color chooser dialog
  3. After selecting a color, the window's background changes to the chosen color
  4. If you cancel the dialog, no change occurs

Key Points

  • Always check if color[1] is not None to handle dialog cancellation
  • Use color[1] (hex format) for setting background colors
  • The color chooser dialog is modal and blocks execution until closed
  • RGB values from color[0] can be used for calculations or custom color operations

Conclusion

The colorchooser module provides an easy way to add color selection functionality to Tkinter applications. Use colorchooser.askcolor() to open the color dialog and apply the returned hex color to change widget backgrounds dynamically.

Updated on: 2026-03-26T18:57:57+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements