I'm trying to make the background image rescale with the window size, but it's not working. How come? how can I solve this?
from tkinter import *
from PIL import Image, ImageTk
window = Tk()
window.geometry("1300x700")
window.title('Monopoly')
background_image = PhotoImage(file="board.png")
background_label = Label(window, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
background_label.pack()
def resizer(event):
global bg1, resized_bg, new_bg
bg1 = Image.open('board.png')
resized_bg = bg1.resize((event.width, event.height))
new_bg = PhotoImage(resized_bg)
background_label.config(image=new_bg)
label = Label(window, text='this is a test').pack()
window.bind('<Configure>', resizer)
window.mainloop()
Your new_bg
variable is going out of scope so you need to keep it alive by doing background_label.img = new_bg
. Also to convert a PIL image to a tkinter image you need to use ImageTk.PhotoImage
. So change your code to:
from tkinter import *
from PIL import Image, ImageTk
window = Tk()
window.geometry("1300x700")
window.title('Monopoly')
background_image = PhotoImage(file="board.png")
background_label = Label(window, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
background_label.pack()
def resizer(event):
global bg1, resized_bg, new_bg
bg1 = Image.open('board.png')
resized_bg = bg1.resize((event.width, event.height))
new_bg = ImageTk.PhotoImage(resized_bg) # Changed this
background_label.img = new_bg # Changed this
background_label.config(image=new_bg)
label = Label(window, text='this is a test').pack()
window.bind('<Configure>', resizer)
window.mainloop()
Also you shouldn't really use both .pack
and .place
on the same widget. You first did this: background_label.place(...)
then this: background_label.pack()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.