Python 如何将图像添加到小部件?为什么不显示图像?

Python 如何将图像添加到小部件?为什么不显示图像?,python,image,tkinter,Python,Image,Tkinter,如何向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很古老,但有一个好处: 必

如何向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很古老,但有一个好处:

必须在Python程序中保留对image对象的引用,方法是将其存储在全局变量中,或将其附加到另一个对象

在第二个版本中,映像是在全局级别声明的

这里有另一个例子来说明这个问题,您希望它也能工作,毕竟它只是一个函数中的同一个代码

不起作用:

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_按钮中的变量是该函数的本地变量。如果您在一个类中遇到这种类型的问题,也会有同样的想法。

可能的重复和几个示例