Displaying pics in Labels with a for Statement using tkinter, can it be done?

前端 未结 1 776

I am trying to get a random bunch of pictures to print side by side; the problem is that if I run the following code all that happens is that it creates a group of blank emp

1条回答
  •  一整个雨季
    2020-12-21 19:02

    This is a well-known issue with tkinter - you MUST keep your own reference to all Photoimages, otherwise python will garbage collect them - that's what's happening to your images. Merely setting them as the image for a label does NOT add to the reference count for the image objects.

    SOLUTION:

    To solve this problem, you'll need a persistent reference to all the image objects you create. Ideally, this would be a data structure in a class namespace, but since you aren't using any classes, a module-level list will have to do:

    pics = [None, None, None, None]   #  This will be the list that will hold a reference to each of your PhotoImages.
    
    def randp(*args):
        w = ['wb.gif', 'wc.gif', 'wd.gif', 'we.gif']
        random.shuffle(w)
        am = 1
    
        for k, i in enumerate(w):    # Enumerate provides an index for the pics list.
            pic = PhotoImage(file=i)
            pics[k] = pic      # Keep a reference to the PhotoImage in the list, so your PhotoImage does not get garbage-collected.
            ttk.Label(mainframe, image=pic).grid(column=am, row=0, sticky=(W, E))
            am+=1
    

    0 讨论(0)
提交回复
热议问题