【问题标题】:Resize background image to window size with Tkinter grid manager使用 Tkinter 网格管理器将背景图像调整为窗口大小
【发布时间】:2023-03-03 17:36:01
【问题描述】:

我不知道如何使用 tkinter 网格管理器将背景图像调整为窗口大小。我的图像单独调整大小,而不调整窗口大小。它与包管理器一起使用,但我想将它与网格管理器一起使用。

from tkinter import *
from PIL import Image, ImageTk

root = Tk()
root.title("Title")
root.geometry("800x600")

class Example(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.grid(sticky=N+S+E+W)
        self.image = Image.open("courbe.gif")
        self.img_copy= self.image.copy()
        self.background_image = ImageTk.PhotoImage(self.image)

        self.background = Label(self, image=self.background_image)
        self.background.grid(row =0, column =0,sticky="nsew")
        self.background.grid_rowconfigure(0, weight=1)
        self.background.grid_columnconfigure(0, weight=1)

        self.background.bind('<Configure>', self._resize_image)

    def _resize_image(self,event):
        new_width = event.width
        new_height = event.height

        self.image = self.img_copy.resize((new_width, new_height))

        self.background_image = ImageTk.PhotoImage(self.image)
        self.background.configure(image =  self.background_image)

e = Example(root)
e.grid(row =0, column =0,sticky="nsew")
e.grid_rowconfigure(0, weight=1)
e.grid_columnconfigure(0, weight=1)

root.mainloop()

【问题讨论】:

    标签: python-3.x tkinter


    【解决方案1】:

    您不应该绑定到背景变化,而是窗口 (master) 变化。然后你可以使用master.winfo_width()master.winfo_height()获取窗口的新高度和宽度。

    所以在你的__init__ 使用

    self.master = master
    self.master.bind('<Configure>', self._resize_image)
    

    并在您的self._resize_image 中使用

    new_width = self.master.winfo_width()
    new_height = self.master.winfo_height()
    

    【讨论】:

      猜你喜欢
      • 2014-07-26
      • 2023-02-11
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 1970-01-01
      • 2014-04-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多