【问题标题】:Why is my background image not resizing itself? How can I solve this?为什么我的背景图片没有自行调整大小?我该如何解决这个问题?
【发布时间】:2021-04-06 20:31:41
【问题描述】:

我正在尝试使背景图像随窗口大小重新缩放,但它不起作用。怎么来的?我该如何解决?

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

【问题讨论】:

  • resizer函数末尾添加background_label.img = new_bg。还将new_bg = PhotoImage(resized_bg) 更改为new_bg = ImageTk.PhotoImage(resized_bg)
  • 可能是因为这个:stackoverflow.com/questions/16424091

标签: python user-interface tkinter


【解决方案1】:

您的new_bg 变量超出范围,因此您需要通过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()

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2020-03-12
  • 2021-09-18
  • 1970-01-01
  • 1970-01-01
  • 2015-06-13
  • 1970-01-01
  • 2016-03-18
  • 1970-01-01
相关资源
最近更新 更多