'How to change bg image in tkinter
I'm making an app in which I want to set an image background to my Canvas. Is it possible? If yes how? I've tried a lot of things but work. Here is the code
from tkinter import *
root=Tk()
bg=PhotoImage(file="bgbg.jpg")
canvas1 = Canvas(root, image=bg,width = 400, height = 800)
canvas1.pack()
Solution 1:[1]
#Import the required library
from tkinter import *
YELLOW = "#f7f5dd"
#Create root
root= Tk()
root.title("My Title")
#define geometry
root.geometry("400x800")
#Load the image
background= PhotoImage(file="example.png")
#Create a canvas
canvas= Canvas(root,width= 400, height= 800)
canvas.pack(expand=True, fill= BOTH)
#Add the image in the canvas -> "nw" = start "North West"
canvas.create_image(0,0,image=background, anchor="nw")
#Add a text in canvas
canvas.create_text(200,400,text="It Works", font= ('Courier 45 bold'), fill=YELLOW)
root.mainloop()
Solution 2:[2]
# Import module
from tkinter import *
# Create object
root = Tk()
# Adjust size
root.geometry("400x400")
# Add image file
bg = PhotoImage(file = "Your_img.png")
# Create Canvas
canvas1 = Canvas( root, width = 400,
height = 400)
canvas1.pack(fill = "both", expand = True)
# Display image
canvas1.create_image( 0, 0, image = bg,
anchor = "nw")
# Add Text
canvas1.create_text( 200, 250, text = "Welcome")
# Create Buttons
button1 = Button( root, text = "Exit")
button3 = Button( root, text = "Start")
button2 = Button( root, text = "Reset")
# 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)
# Execute tkinter
root.mainloop()
Solution 3:[3]
EDIT: Sorry for the late answer Tkinter PhotoImage only supports the GIF, PGM, PPM, and PNG file formats see PythonDocs
If u wanna use .jpeg then u have to use PIL. I changed a few lines at the bottom and it will work with .jpeg (for me)
Try this code. U need a .png-picture
from tkinter import *
root=Tk()
bg=PhotoImage(file="picture.png")
canvas1 = Canvas(root,width = 400, height = 800,bg='red')
canvas1.pack(expand=True,fill='both')
canvas1.create_image((200,400),image=bg,) # (200,400) are x and y cordinates.
root.mainloop()
u need a .jpeg-picture
from tkinter import *
from PIL import Image, ImageTk
root=Tk()
image = Image.open("picture.jpeg")
bg= ImageTk.PhotoImage(image)
canvas1 = Canvas(root,width = 400, height = 800,bg='red')
canvas1.pack(expand=True,fill='both')
canvas1.create_image((200,400),image=bg,) # (200,400) are x and y cordinates.
root.mainloop()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | maniac |
| Solution 2 | Hamdi Mahmoud |
| Solution 3 | maniac |
