Search code examples
pythontkinterbackgroundpng

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


I am trying to set image as background. But I am facing problem like I can't put Label on that gui of tkinter

Here is my code:-

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

Solution

  • When you create the time label, use the background label as the parent. Also remove the pack call since it minimizes borders around widgets.

    Try this code:

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

    Output (my background)

    Time