如何在 tkinter 中将图像添加到小部件?
为什么当我使用这段代码时它不起作用:
some_widget.config(image=PhotoImage(file="test.png"), compound=RIGHT)
但这确实有效吗?
an_image=PhotoImage(file="test.png")
some_widget.config(image=anImage, compound=RIGHT)
最佳答案
当您尝试在第一个版本中使用它时,您的图像正在被垃圾收集。
effbot 很古老,但这里很好 snippet :
You must keep a reference to the image object in your Python program, either by storing it in a global variable, or by attaching it to another object.
在第二个版本中,图像是在全局级别声明的。
这是另一个演示此问题的示例,您希望它也能正常工作,毕竟它只是函数中的相同代码
不起作用:
import tkinter as tk
from PIL import ImageTk
root = tk.Tk()
def make_button():
b = tk.Button(root)
image = ImageTk.PhotoImage(file="1.png")
b.config(image=image)
b.pack()
make_button()
root.mainloop()
有效:
import tkiner as tk
from PIL import ImageTk
root = tk.Tk()
def make_button():
b = tk.Button(root)
image = ImageTk.PhotoImage(file="1.png")
b.config(image=image)
b.image = image
b.pack()
make_button()
root.mainloop()
为什么? make_button
中的变量是该函数的局部变量。如果您在类里面遇到此类问题,也有同样的想法。
关于python - 如何将图像添加到小部件?为什么不显示图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37515847/