In this Python Tkinter tutorial, we will learn how to set background to be an image in Python Tkinter.
Set Background to be an Image in Python Tkinter
- There are more than one ways to add background images but one this is common in all of them that we use the Label widget to set the background.
- The simplest way to do this is to add a background image using PhotoImage() and place other widgets using Place geometry manager.
- Place geometry manager allows users to put the widget anywhere on the screen by providing x & y coordinates. You can even overlap the widgets by providing the same coordinates.
- PhotoImage() takes a file path as an argument and can be used later in code to display images. P
hotoImage(file='image_path.png')
- The Only drawback of using PhotoImage is it works only with png images.
- In case you want to use other formats like jpeg in that case you can use pillow library
- use command:
pip install pillow
to install this library
Code:
In this code, we have added a background image to the Python application. Other widgets like Text and button widgets are placed on the background image.
from tkinter import *
ws = Tk()
ws.title('PythonGuides')
ws.geometry('500x300')
ws.config(bg='yellow')
img = PhotoImage(file="python-tkinter-background-image.png")
label = Label(
ws,
image=img
)
label.place(x=0, y=0)
text = Text(
ws,
height=10,
width=53
)
text.place(x=30, y=50)
button = Button(
ws,
text='SEND',
relief=RAISED,
font=('Arial Bold', 18)
)
button.place(x=190, y=250)
ws.mainloop()
Output:
This is simple a dummy of email sending mechanism but it has a beautiful background image.
You may like the following Python Tkinter tutroials:
- Python tkinter label
- Python Tkinter Entry
- Python Tkinter Button
- Python Tkinter radiobutton
- Python Tkinter Checkbutton
- Python Tkinter Autocomplete
In this tutorial, we have learned how to set background to be an image in Python Tkinter
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.