简体   繁体   English

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

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

I'm trying to set a background image to my tkinter window, however I don't quite know how to resize it so it fits the dimensions of the window.我正在尝试为我的 tkinter window 设置背景图像,但是我不太清楚如何调整它的大小以使其适合 window 的尺寸。 I've looked online, and all the tutorials/answers use pack (to expand and fill), but I can't use pack because I have a bunch of other buttons/labels that all use grid (this is a minimal workable example, my actual script is much bigger with more buttons/larger size).我在网上查看过,所有教程/答案都使用 pack(扩展和填充),但我不能使用 pack,因为我有一堆其他按钮/标签都使用网格(这是一个最小的可行示例,我的实际脚本更大,按钮更多/更大)。 Is there any way to do this using grid?有没有办法使用网格来做到这一点?

This is my current setup:这是我目前的设置:

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

You can use place(x=0, y=0, relwidth=1, relheight=1) to lay out the background image label.您可以使用place(x=0, y=0, relwidth=1, relheight=1)来布置背景图像 label。 In order to fit the image to the window, you need to resize the image when the label is resized.为了使图像适合 window,您需要在调整 label 大小时调整图像大小。

Below is an example based on your code:以下是基于您的代码的示例:

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