Why does Tkinter image not show up if created in a function? Why does Tkinter image not show up if created in a function? tkinter tkinter

Why does Tkinter image not show up if created in a function?


The variable photo is a local variable which gets garbage collected after the class is instantiated. Save a reference to the photo, for example:

self.photo = tkinter.PhotoImage(...)

If you do a Google search on "tkinter image doesn't display", the first result is this:

Why do my Tkinter images not appear? (The FAQ answer is currently not outdated)


from tkinter import *from PIL import ImageTk, Imageroot = Tk()def open_img():    global img    path = r"C:\.....\\"    img = ImageTk.PhotoImage(Image.open(path))    panel = Label(root, image=img)    panel.pack(side="bottom", fill="both")but1 = Button(root, text="click to get the image", command=open_img)but1.pack()root.mainloop() 

Just add global to the img definition and it will work


Just add global photo as the first line inside the function.