简体   繁体   中英

Button image doesn't appear, Tkinter

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!

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM