Welcome folks today in this blog post we will be setting the background image using photoImage widget in tkinter using python. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an app.py
file and copy paste the following code
app.py
1 2 3 4 5 6 7 8 9 10 11 |
# Import module from tkinter import * # Create object root = Tk() # Adjust size root.geometry("400x400") root.mainloop() |
As you can see we are starting the sample tkinter app and inside it we have the window of width 400 and height 400. And then we are starting the tkinter app
by calling the mainloop()
method.
1 2 |
# Add image file bg = PhotoImage(file="profile.png") |
Now as you can see we are setting the background image inside the tkinter
window using the photoImage
widget. And here in this widget we are providing the file
attribute. And inside the file attribute we are providing the path
of the image.
Creating the Canvas
Now we will be creating the canvas inside the tkinter window. For this we are using the Canvas constructor. And inside the constructor we are providing the root reference and also we are providing the width and height of the canvas. And then we are adding the canvas using the pack()
method
1 2 3 4 |
# Create Canvas canvas1 = Canvas(root, width=400,height=400) canvas1.pack(fill="both", expand=True) |
Adding Image in Canvas
Now we will be adding the image
inside the canvas using the create_image()
method and inside it we are providing the x
and y
coordinates and also we are setting the background image using the image attribute. And also we are drawing the text inside the canvas using the create_text()
method. And inside it we are providing the x
and y
coordinates
Adding the Buttons
Now we will be adding the buttons using the button
constructor as shown below
1 2 3 4 |
# Create Buttons button1 = Button(root, text="Exit") button3 = Button(root, text="Start") button2 = Button(root, text="Reset") |
Adding Buttons inside the Canvas
1 2 3 4 5 6 7 8 9 10 11 |
# Display Buttons button1_canvas = canvas1.create_window(100, 10, anchor="nw", window=button1) button2_canvas = canvas1.create_window(100, 40, anchor="nw", window=button2) button3_canvas = canvas1.create_window(100, 70, anchor="nw", window=button3) |
As you can see in the above code we are adding the buttons inside the canvas window using the create_window() method.