How to change the color of a Tkinter label programmatically?


Tkinter Label widgets are used to add text or images to the application. We can even configure the basic properties of labels using the config(options) method. Generally, in order to configure the widgets property dynamically, we use callback functions where we modify the value of attributes.

Example

In this example, we will modify the color Tkinter Labels by defining the callback function. The function can be activated by a button that forces the labels to change the color.

#Import required libraries
from tkinter import *
from tkinter import ttk

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

#Define the geometry of the window
win.geometry("750x250")

#Define a function to Change the color of the label widget
def change_color():
   label.config(bg= "gray51", fg= "white")

#Create a label
label= Label(win, text= "Hey There! How are you?", font= ('Helvetica20 italic'))
label.pack(pady=30)

#Create a Button
ttk.Button(win, text="Change Color", command=change_color).pack(pady=20)
win.mainloop()

Output

Running the above code will display a window that contains a label and a button.

Now, click "Change Color" button to change the color of the Label widget.

Updated on: 04-May-2021

14K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements