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

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


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



This code works:


import tkinter

root = tkinter.Tk()
canvas = tkinter.Canvas(root)
canvas.grid(row = 0, column = 0)
photo = tkinter.PhotoImage(file = './test.gif')
canvas.create_image(0, 0, image=photo)
root.mainloop()



It shows me the image.



Now, this code compiles but it doesn't show me the image, and I don't know why, because it's the same code, in a class:


import tkinter

class Test:
def __init__(self, master):
canvas = tkinter.Canvas(master)
canvas.grid(row = 0, column = 0)
photo = tkinter.PhotoImage(file = './test.gif')
canvas.create_image(0, 0, image=photo)

root = tkinter.Tk()
test = Test(root)
root.mainloop()





Possible duplicate of Cannot Display an Image in Tkinter
– Nae
Nov 25 '17 at 19:26




1 Answer
1



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


photo


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



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



http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Stripe::AuthenticationError No API key provided. Set your API key using “Stripe.api_key = ”

CRM reporting Extension - SSRS instance is blank

Keycloak server returning user_not_found error when user is already imported with LDAP