0

I am populating a grid with frames which are going to hold an image. However when I try to add an image to the frames through a loop, it only adds the image to the very last frame

I had attempted to add the image in the first loop immediately after the frame was created, but that was also only adding the image to the last frame. So I tried adding the images after and met the same result...Each frame should be green but as you can see only the last one is

tileList holds a custom class: Tile, which just holds the path to an image at the moment.

i = 1
j = 0
while i < 4:
    while j < 3:
        frameN = ttk.Frame(root, width=200, height=200, style="tileN.TFrame")
        frameN.grid(row=i, column=j, padx=1, pady=1, sticky="NEWS")
        frameN.grid_propagate(False)
        frameList.append(frameN)
        j = j + 1
    j = 0
    i = i + 1

for tile in frameList:
    # Adding Image to Frame
    img = ImageTk.PhotoImage(Image.open(tileList[0].image))
    label = ttk.Label(tile, image=img)
    label.grid()
  • 2
    See [Why does Tkinter image not show up if created in a function?](https://stackoverflow.com/questions/16424091). It's the same principle: you aren't saving a reference to every image. – Bryan Oakley Apr 17 '23 at 20:55
  • Thank you! I thought it was something like this, but I am not experienced enough with Python yet to fix it. Adding the image to a list fixed it. Weird from Tkinter – Kahler Rockwell Apr 17 '23 at 21:03
  • Please answer your own question instead of adding the answer to the question. – relent95 Apr 18 '23 at 02:15

1 Answers1

0

Incase other people have this issue (or I forget and have it again later) - this is caused by Tkinter Garbage Collection, to bypass this add the image to a list. Related issue with solution

l = []
for tile in frameList:
    # Adding Image to Frame
    img = ImageTk.PhotoImage(Image.open(tileList[0].image))
    l.append(img)
    label = ttk.Label(tile, image=img)
    label.grid()