Skip to content Skip to sidebar Skip to footer

Trying To Put Images From A Folder Onto Tkinter Buttons. Only The Last Image Is Displayed

I'm trying to make a memory card matching game in python and I have a folder called 'icons' that has the 21 images that I want to use. I created the buttons in a 6x7 grid using for

Solution 1:

Since you used same variable icon to hold the reference of PhotoImage instances, so only the final image has variable reference to it. The other images will then be garbage collected.

Add btn.image = icon after each btn.config(image=icon) to keep a reference of the image:

for file in icon_dir.iterdir():
    icon = PhotoImage(file=str(file))
    btn = random.choice(buttons)
    btn.config(image=icon)
    btn.image = icon   # keep a reference to the image
    buttons.remove(btn)
    btn = random.choice(buttons)
    btn.config(image=icon)
    btn.image = icon   # keep a reference to the image
    buttons.remove(btn)

Solution 2:

This line: for file in icon_dir.iterdir():, you are systematically iterating over each image in the directory one after the other, You need to select the images at random from the directory not sequentially.

It goes like this:

/icon_dir
 |_img1
 |_img2
 |_img3

First it assigns img1 to two buttons and removes them, then it assigns img2 to two buttons and removes them then it assigns img3(aka the last image in the folder) to the displayed buttons which you see.

You can use this random.choice(os.listdir(icon_dir)) to get a random image


Post a Comment for "Trying To Put Images From A Folder Onto Tkinter Buttons. Only The Last Image Is Displayed"