如何将 png 文件设置为背景并在 tkinter gui 中使用标签?

How to set png file as background and use Label in tkinter gui?

我正在尝试将图像设置为背景。但我面临的问题是我无法将标签放在 tkinter 的那个 gui 上

这是我的代码:-

from tkinter import *

root=Tk()
root.title("SOHAM MAIL SENDER")
root.iconbitmap("F:\PYTHON PROJECTS\GMAIL\img\Mcdo-Design-Letter-Letter- 
GMail-pen.ico")

root.geometry("900x680")
file = PhotoImage(file = "F:\PYTHON PROJECTS\GMAIL\img\gradient_2.png")
img = Label(root, image=file)
img.place(x=0, y=0, relwidth=1, relheight=1)
img.pack()
def time():
    string = strftime('%I:%M:%S %p')
    label.config(text=string)
    label.after(1000, time)
# time
label = Label(root, font=("ds-digital",35),  background= "#B7C3F9", 
foreground= "white")
time()
label.pack(side=TOP, pady=40)

root.mainloop()

创建时间标签时,使用背景标签作为父标签。同时删除 pack 调用,因为它最小化了小部件周围的边框。

试试这个代码:

from tkinter import *
import datetime

root=Tk()
root.title("SOHAM MAIL SENDER")
root.iconbitmap("F:\PYTHON PROJECTS\GMAIL\img\Mcdo-Design-Letter-Letter-GMail-pen.ico")

root.geometry("900x680")
file = PhotoImage(file = "F:\PYTHON PROJECTS\GMAIL\img\gradient_2.png")
img = Label(root, image=file)
img.place(x=0, y=0, relwidth=1, relheight=1)
#img.pack()
def time():
    string = datetime.datetime.now().strftime('%I:%M:%S %p')
    label.config(text=string)
    label.after(1000, time)
# time
label = Label(img, font=("ds-digital",35),  background= "#B7C3F9", foreground= "white")  # set background as parent
label.place(x=450, y=340, relwidth=.5, relheight=.1, anchor="center")
time()
#label.pack(side=TOP, pady=40)

root.mainloop()

输出(我的背景)

您可以为图片背景和时间使用一个标签:

import tkinter as tk
from time import strftime

root = tk.Tk()
root.title("SOHAM MAIL SENDER")
root.iconbitmap("F:\PYTHON PROJECTS\GMAIL\img\Mcdo-Design-Letter-Letter-GMail-pen.ico")
root.geometry("900x680")

image = tk.PhotoImage(file="F:\PYTHON PROJECTS\GMAIL\img\gradient_2.png")
label = tk.Label(root, image=image, compound='c', font=("ds-digital", 35), fg='white')
label.place(x=0, y=0, relwidth=1, relheight=1)

def show_time():
    cur_time = strftime('%I:%M:%S %p')
    label.config(text=cur_time)
    label.after(1000, show_time)

show_time()

root.mainloop()