繁体   English   中英

如何仅使用网格在 tkinter 中设置背景图像

[英]How to set a background image in tkinter using grid only

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

这是我目前的设置:

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM