[英]Why is my background image not resizing itself? How can I solve this?
I'm trying to make the background image rescale with the window size, but it's not working.我正在尝试使用 window 大小重新缩放背景图像,但它不起作用。 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
.您的new_bg
变量将超出 scope ,因此您需要通过执行background_label.img = new_bg
来保持它的活力。 Also to convert a PIL image to a tkinter image you need to use ImageTk.PhotoImage
.此外,要将 PIL 图像转换为 tkinter 图像,您需要使用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.此外,您不应该在同一个小部件上同时使用.pack
和.place
。 You first did this: background_label.place(...)
then this: background_label.pack()
你首先这样做: background_label.place(...)
然后这个: background_label.pack()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.