首页 > 解决方案 > Tkinter:在背景图像上覆盖标签

问题描述

我正在尝试使用 Python 和 Tkinter 创建我的第一个 GUI。我想要一个根据窗口大小调整大小的背景图像,以及背景顶部的两个标签,两个标签都放在窗口的中间。这两个标签是“全名”和“教育”,如下面的代码所示。

目前,我正在使用 pack() 方法,并且我一直在使用此处的窗口大小调整代码。

我的问题是:如何让标签与背景图像重叠(也是我的代码中的标签)?使用我当前的代码,背景图像似乎位于框架和标签的顶部。

附件是我正在寻找的输出/GUI 的图片,除了我希望我的图像在背景中。

图形用户界面

#Resize using label

from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk

root = Tk()
root.title("Title")
root.geometry('600x600')

def resize_image(event):
    new_width = event.width
    new_height = event.height
    image = copy_of_image.resize((new_width, new_height))
    photo = ImageTk.PhotoImage(image)
    label.config(image = photo)
    label.image = photo #avoid garbage collection

#Background image
image = Image.open("filepath.jpg")
copy_of_image = image.copy()
photo = ImageTk.PhotoImage(image)
label = Label(root, image = photo)
label.bind('<Configure>', resize_image)
label.place(x=0, y=0, relwidth=1, relheight=1)
label.pack(fill=BOTH, expand = YES)
label.lower()

frame = Frame(root, width=600, height=600, relief='raised', borderwidth=2)
frame.pack(fill="both", expand=True)
frame.pack_propagate(False) 

#Top Frame
top_frame = Frame(frame,width=600, height=350)
top_frame.pack(side = TOP)

#Various Labels
Label(frame, text = 'Full Name', width = 8).pack()
Label(frame, text = 'Education', width = 8).pack()

root.mainloop() 

标签: pythontkinterbackground-image

解决方案


一些重新安排是有序的。您的大号frame位于背景图像之上,完全覆盖了它。所以,让我们将背景Label作为 的一部分frame,而不是root。您可能应该选择其中之一place()pack()但不应该两者兼而有之。为了让其他标签居中,我创建了一个居中的框架并将它们打包到其中。可能还有其他方法可以做到这一点:

from tkinter import *
from PIL import Image, ImageTk

def resize_image(event):
    new_width = event.width
    new_height = event.height

    image = copy_of_image.resize((new_width, new_height))
    photo = ImageTk.PhotoImage(image)

    label.config(image=photo)
    label.image = photo  # avoid garbage collection

root = Tk()
root.title("Title")
root.geometry('600x600')

frame = Frame(root, relief='raised', borderwidth=2)
frame.pack(fill=BOTH, expand=YES)
frame.pack_propagate(False)

copy_of_image = Image.open("filepath.jpg")
photo = ImageTk.PhotoImage(copy_of_image)

label = Label(frame, image=photo)
label.place(x=0, y=0, relwidth=1, relheight=1)
label.bind('<Configure>', resize_image)

center_frame = Frame(frame, relief='raised', borderwidth=2)
center_frame.place(relx=0.5, rely=0.5, anchor=CENTER)

Label(center_frame, text='Full Name', width=8).pack()
Label(center_frame, text='Education', width=8).pack()

root.mainloop()

推荐阅读