Arnold Johnson
Arnold Johnson

Reputation: 37

ImageTK not rendering image

I am trying to make a 5x5 grid of randomly generated images. When I run the following code, the window pops up in the correct size, but none of the images that were supposed to be in the labels:

col = 0
for array in (a,b,c,d,e):
    ro = 0
    for item in array:
        if item == 0:
            path = "W.jpg"
        elif item == 1:
            path = "P.jpg"
        elif item == 2:
            path = "D.jpg"
        elif item == 3:
            path = "H.jpg"
        elif item == 4:
            path = "M.jpg"
        elif item == 5:
            path = "F.jpg"
        img = ImageTk.PhotoImage(Image.open(path))
        Label(window, image = img).grid(column = ro, row = col)
        ro += 1
    col += 1
print(final)

Upvotes: 0

Views: 54

Answers (1)

acw1668
acw1668

Reputation: 47173

As img will be overwritten by new instance of ImageTk.PhotoImage(...) in for loop, so the previous reference of img will be lost and the previous image will be destroyed. To overcome it, declare a global list to hold the image reference as below:

imagefiles = ['W.jpg', 'P.jpg', 'D.jpg', 'H.jpg', 'M.jpg', 'F.jpg']
images = [] # list to hold the image references
for col, array in enumerate((a, b, c, d, e)):
    for ro, item in enumerate(array):
        images.append(ImageTk.PhotoImage(Image.open(imagefiles[item]))) # save the image reference
        Label(window, image=images[-1]).grid(row=col, column=ro)

Or you can attach the image reference to the Label instance as below:

imagefiles = ['W.jpg', 'P.jpg', 'D.jpg', 'H.jpg', 'M.jpg', 'F.jpg']
for col, array in enumerate((a, b, c, d, e)):
    for ro, item in enumerate(array):
        lbl = Label(window)
        lbl.grid(row=col, column=ro)
        lbl.image = ImageTk.PhotoImage(Image.open(imagefiles[item])) # attach the image reference to label instance variable
        lbl.config(image=lbl.image)

Upvotes: 1

Related Questions