如何在 tkinter 中使用 askopenfilename 将图像添加到文本小部件?

问题描述

我正在尝试找到一种在 tkinter.text 小部件中添加图像的方法。我在 Stackoverflow 中找到了很多答案,比如 thisthis。但是这些都没有回答我关于如何使用 askopenfilename 方法添加图像的问题。

一些代码

from tkinter import *
import tkinter.filedialog as fd


def add_image():
    global i
    file1 = fd.askopenfilename(filetypes=[("Image files","*.png")])
    i = PhotoImage(file=file1)
    text.image_create(END,image=i)


root = Tk()

text = Text(root,height=50,width=200) 
text.pack() 

Button(root,text="Insert",command=add_image).pack()

root.mainloop()

我会感谢任何帮助我的人!

解决方法

这是改进的代码,现在每个图像都被“保存”到字典中,这样它就不会被垃圾收集(正如@CoolCloud 提到的),现在它应该能够将几乎任何数量的图像添加到一个去多个,不知道如果图像被删除会发生什么,无论它是否留在字典中:

from tkinter import *
import tkinter.filedialog as fd
from PIL import ImageTk,Image


images = dict()


def add_image():
    files = fd.askopenfilenames(filetypes=[("Image files","*.png")])
    for file in files:
        file_name = file + str(len(images))
        images[file_name] = ImageTk.PhotoImage(Image.open(file))
        text.image_create('end',image=images[file_name])


root = Tk()

text = Text(root,height=25,width=200)
text.pack()

Button(root,text="Insert",command=add_image).pack()

root.mainloop()

哦,如果你没有你将不得不pip install pillow