[英]Button image doesn't appear, Tkinter
I'm currently having a problem while trying to assign images to buttons in a for loop:我目前在尝试将图像分配给 for 循环中的按钮时遇到问题:
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.其中 letter 是字母表中的一个字母(字符串)。 I have 26 png each one for a letter of the alphabet, in this function I create only 16 buttons with letters pictures.我每个字母都有 26 个 png,在这个功能中,我只创建了 16 个带有字母图片的按钮。 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.我知道这与 python 垃圾收集器有关。 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 .另一件事,我可以获得想要的结果,但我需要手动创建每个 PhotoImage 实例,如果可能的话,我想避免这种情况,我还应该提到我正在一个类中完成所有这些。 Thank you for your help!感谢您的帮助!
You did not save the reference of tk.PhotoImage
used in b = tk.Button(...)
.您没有保存b = tk.Button(...)
使用的tk.PhotoImage
的引用。 Also you assigned the result of self.letter_typed(...)
to command
argument of tk.Button
.另外你分配的结果self.letter_typed(...)
以command
的参数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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.