Reputation: 944
I'm currently having a problem while trying to assign images to buttons in a for loop:
for index in range(16):
b = tk.Button(button_frame, text = letter,image = tk.PhotoImage(file = letter+".png"),
command= self.letter_typed(letter, word_label))
b.image = tk.PhotoImage(file = letter+".png")
b.grid(row = index//4, column = index%4)
where letter is a letter (string) of the alphabet. I have 26 png each one for a letter of the alphabet, in this function I create only 16 buttons with letters pictures. Problem is that the picture doesn't appear, only a blank case that has the same size as the picture wanted. I know this has something to do with python garbage collector. Another thing, I can obtain the result wanted but I need to create manually each PhotoImage instance, and I would like to avoid that if possible, also I should mention that I'm doing all of this in a class. Thank you for your help!
Upvotes: 0
Views: 128
Reputation: 46678
You did not save the reference of tk.PhotoImage
used in b = tk.Button(...)
. Also you assigned the result of self.letter_typed(...)
to command
argument of tk.Button
.
Fixed code:
for index in range(16):
tkimg = tk.PhotoImage(file=letter+'.png')
b = tk.Button(button_frame, text=letter, image=tkimg,
command=lambda: self.letter_typed(letter, word_label))
b.image = tkimg
b.grid(row=index//4, column=index%4)
Upvotes: 1