简体   繁体   中英

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. 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). 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. In order to fit the image to the window, you need to resize the image when the label is resized.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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