Search code examples
pythonuser-interfacetkintertkinter-label

Label not showing a Picture as a background in Tkinter


#importing everything
from tkinter import *
from PIL import Image

#making the root window
root = Tk()

dimension = '800x500'
#setting the window
im = Image.open(r'C:\Users\Hunter\Desktop\school 1\module\pbm\bg.png')
bg = PhotoImage(im)
window = Label(root, bd=0, height=70, width=50)
window.image=bg
window.pack(fill=Y, expand=True, side=BOTTOM)

#overriding the default properties
root.overrideredirect(True)

root.geometry(dimension)


#the main title bar
title_bar = Frame(root, bg='#496E82', bd=0, height=4)


#pack all the widgets
title_bar.pack(fill=X, side=TOP)



#code for moving the window
def get_pos(event):
    xwin = root.winfo_x()
    ywin = root.winfo_y()
    startx = event.x_root
    starty = event.y_root

    ywin = ywin - starty
    xwin = xwin - startx
    def move_window(event):
        root.geometry(dimension + '+{0}+{1}'.format(event.x_root + xwin, event.y_root + ywin))
    startx = event.x_root
    starty = event.y_root
    title_bar.bind('<B1-Motion>', move_window)


#binding the title bar so that it moves
title_bar.bind('<Button-1>', get_pos)


#main thing
root.mainloop()

And when I run the code above, it hides everything and the only thing it shows, is a White Window, nothing else. It also hides the Frame (Title Bar), at the top. But when I set a background color to the Label, then also, it hides everything, the Frame and everything and it shows that color's window. The thing I wanna do it add a background picture to my application, and then add other tkinter widgets, like Labels, Buttons etc. on the top of the background picture. Help would be appreciated!!

EDIT: This is what happens when I remove the height and width attributes from the Label. How to make the image cover the y-axis as well, instead of just covering x-axis. And it also eats up the Frame at the top. How to fix all this?


Solution

  • As long as the image is png file, you can continue using tk.PhotoImage, else use PIL.ImageTk.PhotoImage. And tk.PhotoImage does not accept a PIL image object as their file, you should say:

    bg = PhotoImage(file=r'image-from-rawpixel-id-2023082-png.png')
    

    ...and you have not set the image option to the label:

    window = Label(root, image=bg, bd=0, height=70, width=50)
    

    EDIT: To take the actual size of the image, remove height and width of the label:

    window = Label(root, image=bg, bd=0)
    

    You can put widgets above this label, by using place(x=n,y=m) geometric manager.