【问题标题】:Blank images when attempting to load image into tkinter window尝试将图像加载到 tkinter 窗口时出现空白图像
【发布时间】:2020-07-22 13:01:25
【问题描述】:

所以发生的事情是我的目录中保存了一个 PNG 文件。我正在尝试创建一个程序,将这张图片加载到窗口上 3 次。我正在将 tkinter 用于 UI 及其 PhotoImage 类来执行此操作。要加载图片,我通常会创建一个类,然后加载一个带有“图像参数”的按钮。但是,当我尝试运行该程序时,它只加载第三张图片。第一个和第二个只是显示为空白框。有人可以帮助我吗? 代码如下:

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()

【问题讨论】:

  • 对不起,请忽略“添加”功能。我将它用于其他用途,但我忘了删除它
  • 如果所有按钮都使用同一张图片,为什么不把imageClass = PhotoImage(...)这一行移到for循环之前呢?
  • 是的,非常感谢

标签: python image tkinter python-3.7 tk


【解决方案1】:

发生的情况是,您的图像被存储在for 循环的每次迭代 中作为imageClass = PhotoImage(file="updated.png")

imageClass 为每个 i 覆盖其值,当循环最终退出时,imageClass 中的 一个 引用仅保留,因此第三张图像出现而其他图像没有出现。

因此,您需要将每个 PhotoImage “引用”存储在某处,例如在全局字典中

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()

【讨论】:

  • 哦,我现在完全明白了!非常感谢所有帮助过我的人
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-25
  • 1970-01-01
  • 2020-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-25
相关资源
最近更新 更多