【问题标题】:Button image doesn't appear, Tkinter按钮图像没有出现,Tkinter
【发布时间】:2020-01-20 17:30:23
【问题描述】:

我目前在尝试将图像分配给 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)

其中 letter 是字母表中的一个字母(字符串)。我每个字母有 26 个 png,在这个函数中我只创建了 16 个带有字母图片的按钮。 问题是图片没有出现,只有一个与所需图片大小相同的空白案例。我知道这与 python 垃圾收集器有关。 另一件事,我可以获得想要的结果,但我需要手动创建每个 PhotoImage 实例,如果可能的话,我想避免这种情况,我还应该提到我正在做所有这些在一个类中。感谢您的帮助!

【问题讨论】:

标签: python tkinter


【解决方案1】:

您没有保存在b = tk.Button(...) 中使用的tk.PhotoImage 的引用。您还将self.letter_typed(...) 的结果分配给tk.Buttoncommand 参数。

固定代码:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-20
    • 2012-04-20
    • 2017-01-31
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多