0

please help to understand the cause of the phenomenon.

This script does not work (can not see images).

import os, sys
from tkinter import *
from PIL.ImageTk import PhotoImage

DIR_IMGS = 'imgs'
imgfiles = os.listdir(DIR_IMGS)
main = Tk()

for imgfile in imgfiles:
    win = Toplevel()
    imgpath = os.path.join(DIR_IMGS, imgfile)
    objImg = PhotoImage(file=imgpath)
    Label(win, image=objImg).pack()

main.mainloop()

and this script works (see images).

import os, sys
from tkinter import *
from PIL.ImageTk import PhotoImage         

imgdir = 'images'
imgfiles = os.listdir(imgdir)               
main = Tk()

savephotos = [] #?????????????????????

for imgfile in imgfiles:
        imgpath = os.path.join(imgdir, imgfile)
        win = Toplevel()
        win.title(imgfile)

        imgobj = PhotoImage(file=imgpath)
        Button(win, image=imgobj).pack()     
        savephotos.append(imgobj)   #?????????????????????

main.mainloop()

they differ only in two rows. it is unclear why such great importance "savephotos"

Sergey
  • 869
  • 2
  • 13
  • 22
  • possible duplicate of [Tkinter Label does not show Image](http://stackoverflow.com/questions/13148975/tkinter-label-does-not-show-image) – FabienAndre Feb 09 '14 at 16:51
  • 2
    In the first case, the PhotoImage object is orphan (not referenced in python part) and thus garbage collected (cleaned from memory). In the second case, you keep a reference to it preventing it to be GCed. – FabienAndre Feb 09 '14 at 16:54

1 Answers1

0

As FabienAndre writes in the second comment. The garbage collector deletes the image object. The image must be retained for the duration of the display.

I tried a simple code modification:

import os, sys
from tkinter import *
from PIL.ImageTk import PhotoImage

DIR_IMGS = 'imgs'
imgfiles = os.listdir(DIR_IMGS)
main = Tk()

objImgList = []
for imgfile in imgfiles:
    win = Toplevel()
    imgpath = os.path.join(DIR_IMGS, imgfile)
    objImg = PhotoImage(file=imgpath)
    Label(win, image=objImg).pack()
    objImgList.append(objImg)

main.mainloop()

All pictures are now displayed.