Dynamically change the widget background color in Tkinter


To configure the widget's properties in a Tkinter application, we generally use the 'configure(**options)' method. We can customize the background color, font property, and other specific properties of the widget in the application.

There might be a case when we want to dynamically change the background color of the widget. Though, we can also define the list of colors and change the color while iterating over the list.


#Import the required libraries
from tkinter import *
from random import shuffle
import time

#Create an instance of Tkinter frame
win = Tk()

#Add fonts for all the widgets
win.option_add("*Font", "aerial")

# Define the backround color for all the widgets
def change_color():
   colors= ['#e9c46a','#e76f51','#264653','#2a9d8f','#e85d04','#a2d2ff','#06d6a0','#4d908e']
   while True:
      for i in range(0,len(colors)):

#Display bunch of widgets
label=Label(win, text="Hello World", bg= 'white')
label.pack(pady= 40, padx= 30)

#Create a Button to change the background color of the widgets
btn=Button(win, text="Button", command= change_color)
btn.pack(pady= 10)


When we compile the above code, it will display a window with a Label widget and a Button.

When we press the button, it will call the change_color() function which changes the background color of the window dynamically.

Published on 25-May-2021 09:22:15