How to change a Tkinter window background color
Tkinter is one of the GUI modules available in Python. It comes with the Python standard library. It is used to create cross-platform desktop GUI applications. It is lightweight and easy to use compared to other GUI modules available in Python. In this answer, we'll learn to change the background color of the Tkinter window.
Syntax
#using configurewindow.configure(bg="provide your color here")#using bg propertywindow['bg'] = "provide your color here"#using background propertywindow['background'] = "provide your color here"
We can specify the color with the color name or use the hex value.
Code example
Let's look at an example below:
# Import the Tkinter library
from tkinter import *
# Create an instance of Tkinter window
window=Tk()
# Set the size of the window
window.geometry("300x300")
# Set the window background color
window.configure(bg="red")
#Uncomment below lines to use
# set the window background color using bg or background property
# window['bg'] = "#32a2a8"
# window['background'] = "#8732a8"
# Create a label widget
label=Label(window, text="Hello from Educative !!!").pack()
window.mainloop()Code explanation
In the above code snippet:
Line 5: We create an instance of the Tkinter class
Tk()and assign it to the variablewindow.Line 8: We set the size of the window as
300x300px using the geometry method.Line 11: We set the background color of the window as
redby passingredas value to thebgattribute in theconfiguremethod.Line 20: We create a label using the
Label()widget.
Free Resources