2

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
Kwan Hui
  • 21
  • 3
  • 2
    [This](https://stackify.com/python-garbage-collection/) could answer your question. – Thingamabobs Dec 25 '20 at 09:43
  • 2
    The `PhotoImage` in the second case exists only long enough for the `create_image()` call to complete. Apparently that's not long enough for it be displayed. I think the fact that tkinter doesn't increment the reference count of image objects which is what normally happens in Python code, and this is why saving in in a local variable often causes problems. This could happen if you put the first code inside a function, for example. – martineau Dec 25 '20 at 11:22
  • @martineau So not saving it as a variable was a problem because the image disappears too quickly as tkinter does not "increment the reference count of image". I have not tried using it in a function yet. Thank you for taking the time to explain in a way that I can understand! – Kwan Hui Dec 27 '20 at 02:53
  • 1
    @Atlas435 thanks for the interesting link about garbage collection. I understand more about how things work after reading it! – Kwan Hui Dec 27 '20 at 02:58

0 Answers0