Setting Background color for Tkinter in Python

TkinterPythonServer Side ProgrammingProgramming

We can customize the tkinter widgets using the tkinter.ttk module. Tkinter.ttk module is used for styling the tkinter widgets such as setting the background color, foreground color, activating the buttons, adding images to labels, justifying the height and width of widgets, etc.

In order to add a background color in tkinter widgets, we can specify the background property in the widget.


In the following example, we will create a button that will change the background of the text label.

#Import the tkinter library
from tkinter import *
from tkinter.ttk import *

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

#Set the geometry

#Add a class to style the tkinter widgets

style = ttk.Style()
style.configure('TEntry', foreground = 'red')

#Define a function to change the text color
def change_color():

#Create a text widget
text=Label(win,text="This is a New Text",foreground="black",
background="yellow",font=('Aerial bold',20))

#Create a Button widget
Button(win, text= "Click Here", command= change_color).pack(pady=10)


Running the above code will create a window containing a text label with a "yellow" background color.

Now, click the "Click Here" button. It will change the background color of the text label to "Red".

Published on 26-Mar-2021 10:19:59