0

So what's happening is that I have a PNG file saved in my directory. I am trying to create a program that loads this picture onto a window 3 times. I am using tkinter for the UI and its PhotoImage class to do this. To load a picture I normally create a class and then load put a button in it with the 'image parameter'. However, when I try to run this program, it only loads the 3rd picture. The 1st and 2nd one just appear as blank boxes. Can somebody help me? The code is below:

from tkinter import *

def add():
    imageClass = PhotoImage(file="updated.png")
    button = Button(root, compound=TOP, image=imageClass, pady=20, bd=0, highlightthickness=0)
    button.pack()

root = Tk()

root.config(bg="white")

for i in range(3):
    root.update()
    imageClass = PhotoImage(file="updated.png")
    button = Button(root, compound=TOP, image=imageClass, pady=20, bd=0, highlightthickness=0)
    button.pack()
root.mainloop()
Harman Punchi
  • 85
  • 2
  • 9

1 Answers1

0

What's happening is your images are being stored on every iteration of the for loop as imageClass = PhotoImage(file="updated.png")

imageClass gets its value overriden for every i, and when the loop finally exits only one reference in imageClass remains, hence why the 3rd image appers and others do not.

Thus you need to store every PhotoImage "reference" somewhere, for example in a global dictionary

root = Tk()

# Modification 1
myImageClasses = dict()

root.config(bg="white")

for i in range(3):
    root.update()
    # Modification 2
    myImageClasses[i] = PhotoImage(file="updated.png")
    button = Button(root, compound=TOP, image=myImageClasses[i], pady=20, bd=0, highlightthickness=0)
    button.pack()

root.mainloop()

Space
  • 142
  • 1
  • 7