# How to change the color of a Tkinter label programmatically?

TkinterServer Side ProgrammingProgramming

#### Mastering Python GUI with Tkinter

16 Lectures 2 hours

#### GUI Programming with Python Tkinter and Java Swing

30 Lectures 3.5 hours

#### Build A Paint Program With TKinter and Python

24 Lectures 1.5 hours

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 14:27:43

Advertisements