- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Example
#Import the required libraries from tkinter import * from random import shuffle import time #Create an instance of Tkinter frame win = Tk() win.geometry("700x250") #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: shuffle(colors) for i in range(0,len(colors)): win.config(background=colors[i]) win.update() time.sleep(1) #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) win.mainloop()
Output
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.
Advertisements