簡體   English   中英

Tkinter:在背景圖片上方覆蓋標簽

[英]Tkinter: Overlaying a label on top of a background image

我正在嘗試使用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() 

需要重新安排一些順序。 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM