Why does image fails to display in tkinter unless PhotoImage is saved as a variable?

321 Views Asked by At

I just started learning python recently. I have tried to use Thonny. I googled and searched on stackoverflow such as Why does Tkinter image not show up if created in a function? and Tkinter.PhotoImage doesn't not support png image, but have not found similar questions yet... I have tried to read documentation, but am struggling.

The image displays correctly when I saved the PhotoImage as a variable and then used canvas.create_image:

tomato_img = PhotoImage(file="/Users/kwanh/PycharmProjects/day-28/tomato.png")

canvas.create_image(110, 112, image=tomato_img)

However, when I did not save the PhotoImage as a variable, the image no longer displays:

canvas.create_image(110, 112, image=PhotoImage(file="/Users/kwanh/PycharmProjects/day-28/tomato.png"))

I guess I can just save it as a variable but would like to know if it is because I have done something wrong? I used the type functions to check that the variable or without variable is of <class 'tkinter.PhotoImage'> Thank you.

0

There are 0 best solutions below