[英]Why is my background image not resizing itself? How can I solve this?
我正在嘗試使用 window 大小重新縮放背景圖像,但它不起作用。 怎么來的? 我該如何解決這個問題?
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()
您的new_bg
變量將超出 scope ,因此您需要通過執行background_label.img = new_bg
來保持它的活力。 此外,要將 PIL 圖像轉換為 tkinter 圖像,您需要使用ImageTk.PhotoImage
。 因此,將您的代碼更改為:
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()
此外,您不應該在同一個小部件上同時使用.pack
和.place
。 你首先這樣做: background_label.place(...)
然后這個: background_label.pack()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.