Python 插入图像tkinter

Python 插入图像tkinter,python,tkinter,python-imaging-library,Python,Tkinter,Python Imaging Library,最近,我正在使用Python的Tkinter库开发一个项目文本编辑器。我试图制作一个函数,在文本区域插入图像 def insertImage(): select_image = filedialog.askopenfilename(title="Select your image",filetypes=[("Image Files", "*.png"), ("Image Files", "*.jpg

最近,我正在使用Python的Tkinter库开发一个项目文本编辑器。我试图制作一个函数,在文本区域插入图像

def insertImage():
    select_image = filedialog.askopenfilename(title="Select your image",filetypes=[("Image Files", "*.png"), ("Image Files", "*.jpg")])
    global img
    img = ImageTk.PhotoImage(file=select_image)
    content_text.image_create(END, image=img)
当我尝试插入第一个图像时,效果很好,但当我在编辑器中插入第二个图像时,第一个图像变为不可见或白色

我已经导入了所有必要的库,如tkinter、filedialog、PIL等。 你能告诉我代码中有什么问题吗?或者你能提供正确的解决方案吗。
提前谢谢

这是因为您对图像使用了相同的全局变量
img
。当选择新图像并将其分配给
img
,则没有引用前一图像的变量,因此将对其进行垃圾收集

使用
列表
存储打开的图像:

imagelist=[]
def insertImage():
选择_image=filedialog.askopenfilename(title=“选择您的图像”,文件类型=[(“图像文件”,“*.png”),(“图像文件”,“*.jpg”)]))
如果选择_图像:
append(ImageTk.PhotoImage(file=select_image))
content\u text.image\u create(tk.END,image=imagelist[-1])

您能为您所说的内容提供代码吗?@tanishakavashisht回答已用示例代码更新。是的,现在它工作正常。谢谢你的帮助。