【问题标题】:How to set a background image in tkinter using grid only如何仅使用网格在 tkinter 中设置背景图像
【发布时间】:2020-10-07 08:37:21
【问题描述】:

我正在尝试为我的 tkinter 窗口设置背景图像,但是我不太清楚如何调整它的大小以使其适合窗口的尺寸。我在网上看过,所有的教程/答案都使用包(扩展和填充),但我不能使用包,因为我有一堆其他按钮/标签都使用网格(这是一个最小的可行示例,我的实际脚本更大,按钮更多/更大)。有没有办法使用网格来做到这一点?

这是我目前的设置:

import tkinter as tk
from PIL import ImageTk, Image

root = tk.Tk()
background_image = ImageTk.PhotoImage(Image.open("pretty.jpg"))
l=tk.Label(image=background_image)
l.grid()

tk.Label(root, text="Some File").grid(row=0)
e1 = tk.Entry(root)
e1.grid(row=0, column=1)


tk.mainloop()

【问题讨论】:

  • packgrid 甚至 place 都不会调整图像大小。您可以将图像设置为适当的大小。
  • 如果你想让图像出现在所有东西的后面,你需要给它rowspan/columnspan 选项,使它覆盖其他小部件使用的每一行/列。按照您现在的方式,条目 不能 与图像重叠,因为它们位于不同的列中。
  • 您可以使用place()
  • 这能回答你的问题吗? what-does-weight-do-in-tkinter
  • @jasonharper 如果我展开我的 tkinter 窗口(即单击展开按钮),这将不起作用,我希望图像“适合”/“填充”窗口尺寸,即使它们改变

标签: python tkinter


【解决方案1】:

您可以使用place(x=0, y=0, relwidth=1, relheight=1) 来布置背景图片标签。为了使图像适合窗口,您需要在调整标签大小时调整图像大小。

以下是基于您的代码的示例:

import tkinter as tk
from PIL import Image, ImageTk

def on_resize(event):
    # resize the background image to the size of label
    image = bgimg.resize((event.width, event.height), Image.ANTIALIAS)
    # update the image of the label
    l.image = ImageTk.PhotoImage(image)
    l.config(image=l.image)

root = tk.Tk()
root.geometry('800x600')

bgimg = Image.open('pretty.jpg') # load the background image
l = tk.Label(root)
l.place(x=0, y=0, relwidth=1, relheight=1) # make label l to fit the parent window always
l.bind('<Configure>', on_resize) # on_resize will be executed whenever label l is resized

tk.Label(root, text='Some File').grid(row=0)
e1 = tk.Entry(root)
e1.grid(row=0, column=1)

root.mainloop()

【讨论】:

  • 感谢您的成功!我只是想确保我了解这里发生了什么。有趣的 on_resize 获取图像,并在标签大小更改时调整其大小。它将尺寸更改为准确的标签尺寸。我对 l.config 在做什么有点困惑。之后,图像像往常一样上传,l.place 只是将它适合窗口,然后 l.bind 说当标签大小发生变化时,改变图像的大小(通过 on_resize)。我理解正确吗?
  • bind() 用于注册回调,当某些条件发生时将执行该回调。 &lt;Configure&gt; 用于几何更改。 l.place(...) 用于使标签适合父窗口,因此每当调整窗口大小时,标签也会调整大小,因此将执行on_resize() 函数。 l.config() 用于设置一些属性,例如文字、图片、前景色等
猜你喜欢
  • 2021-10-12
  • 2013-11-26
  • 2011-03-07
  • 2022-07-11
  • 2017-12-08
  • 1970-01-01
  • 1970-01-01
  • 2014-05-08
  • 1970-01-01
相关资源
最近更新 更多