Noir
Noir

Reputation: 171

How to dynamically insert a random number of images into the window

I have the following code:

import tkinter as tk

data = [['A',1],['B',2],['C',3],['D',4]]

def ranking():
    root = tk.Tk() 
    root.focus_force() 

    windowWidth = root.winfo_reqwidth()
    windowHeight = root.winfo_reqheight()
    positionRight = int(root.winfo_screenwidth()/2 - windowWidth/2)
    positionDown = int(root.winfo_screenheight()/2 - windowHeight/2)
    root.geometry("+{}+{}".format(positionRight, positionDown))

    for i in range(0,len(data)):
        tk.Label(image=tk.PhotoImage(file="D:\\A\\" + data[i][0] + ".gif")).grid(row=data[i][1]-1, column=0)

    root.mainloop()

ranking()

What I want to do is to have a random number of pictures (whatever is inserted in data at any moment), displayed within the window (in the order as indicated within the data), yet if I currently run the code it simply results in a blank window.The names of the pictures are literally A, B, C...and they display without a problem if I use something like (this is an extract from another piece of code I wrote):

img2 = tk.PhotoImage(file="D:\\A\\" + choice2 + ".gif")
label_img2 = tk.Label(image=img2)
label_img2.grid(row=2, column=1)

Any guidance would be very welcome as I am still quite new with working with tkinter!

Upvotes: 1

Views: 66

Answers (1)

Kenly
Kenly

Reputation: 26698

When you add a PhotoImage or other Image object to a Tkinter widget, you must keep your own reference to the image object. If you don’t, the image won’t always show up.

The problem is that the Tkinter/Tk interface doesn’t handle references to Image objects properly; the Tk widget will hold a reference to the internal object, but Tkinter does not. When Python’s garbage collector discards the Tkinter object, Tkinter tells Tk to release the image. But since the image is in use by a widget, Tk doesn’t destroy it. Not completely. It just blanks the image, making it completely transparent…

The solution is to make sure to keep a reference to the Tkinter object, for example by attaching it to a widget attribute:

for i in range(0,len(data)):
    photo = tk.PhotoImage(file="D:\\A\\" + data[i][0] + ".gif")
    label = tk.Label(image=photo )
    label.image = photo  # keep a reference!
    label.grid(row=data[i][1]-1, column=0)

Taken from Why do my Tkinter images not appear?

Upvotes: 1

Related Questions