Setting Background color for Tkinter in Python


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.

Example

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
win.geometry("600x400")

#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():
   text.configure(background="red")

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

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

Output

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".

Updated on: 26-Mar-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements