[英]how to set background image to a window using Tkinter python 2.7
[英]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.