-1

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()
  • Add `background_label.img = new_bg` at the end of the `resizer` function. Also change `new_bg = PhotoImage(resized_bg)` to `new_bg = ImageTk.PhotoImage(resized_bg)` – TheLizzard Apr 06 '21 at 20:35
  • It's likely due to this: https://stackoverflow.com/questions/16424091 – Bryan Oakley Apr 06 '21 at 20:36

1 Answers1

0

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()

TheLizzard
  • 7,248
  • 2
  • 11
  • 31