I'm trying to add a background to a tk.TopLevel() window.
I have succeeded using the same code as follows to add a bakground to a tk.Tk(). However, the same code doesn't work and leaves me with the default background.
def add_window_launching():
#initializing window
add_window=tk.Toplevel()
add_window.title("Inventaire Petits Débrouillards")
add_window.geometry('900x350')
add_window.resizable(width=False, height=False)
#Setting background
raw_image=Image.open("C:/Users/Ordinateur/Desktop/db-update-petits-debrouillards/UI/ajout.png")
background_image=ImageTk.PhotoImage(raw_image)
background_label = tk.Label(add_window, image=background_image)
#Adding widgets
welcome_text=tk.Label(add_window, text="Text")
object_description=tk.Label(add_window, text="Description de l'objet :")
description_entry=tk.Entry(add_window, width=100)
row=SQL.Entries([description_entry], add_window)
submit_button=tk.Button(add_window, text="Ajouter", command=row.adding_entry)
#Organizing window
background_label.place(x=0, y=0, relwidth=1, relheight=1)
welcome_text.place(anchor="n", relx=0.5, rely=0.25)
object_description.place(anchor="nw", relx=0.08, rely=0.5)
description_entry.place(anchor="ne", relx=0.92, rely=0.5)
submit_button.place(anchor="n", relx=0.5, rely=0.75)
Here is the result of the execution of the script. Top window is the main window, bottom window is the TopLevel one. Backgrounds must be identic. I can't post images because my account is new but you'll find the result i got here. Any ideas why it doesn't work ?
There is bug in PhotoImage
.
Garbage Collector
removes image from memory when it is assigned to local variable in function and then you can't see image.
You have to assign image to global variable or to some widget. It is popular to assign to Label
which displays this image:
background_label.image = background_image
Doc: PhotoImage