Tkinter文本小部件图像插入

时间:2019-10-19 08:42:32

标签: python-3.x tkinter

我制作了一个文本小部件来写问题。我想在按下添加图像按钮时插入图像。我怎样才能做到这一点?当我选择其他图像时,第一个图像将被删除。现在,我可以使用以下代码添加一张图片:

import tkinter as tk
root = tk.Tk()
root.geometry('800x520+0+0')
global img
img = tk.PhotoImage(file="quiz.gif")
def add_img():
    T.image_create(tk.INSERT, image=img)
tk.Button(root, text="Add Image", font=('Verdana',8), 
command=add_img).place(x=690, y=0)
T = tk.Text(root, width=65, height=17, padx=10, pady=10, font=('Verdana', 
14), wrap='word')
T.place(x=0, y=0)
root.mainloop()

我想在使用tk-listbox选择时添加其他图像。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我用字典来解决问题。

import tkinter as tk, glob
root = tk.Tk()
root.geometry('800x520+0+0')
Images = {}
for infile in glob.glob('*.gif'):
    img = infile[:-4]
    if img not in Images:
        Images[img] = tk.PhotoImage(file=infile)
def add_img():
    global listbox
    listbox = tk.Listbox(root, font=('Verdana',9), width=12)
    listbox.place(x=60,y=2)
    for infile in glob.glob('*.gif'):
        listbox.insert(tk.END, infile[:-4])
    listbox.bind('<<ListboxSelect>>',CurSelet)
def CurSelet(event):
    fn = listbox.get(tk.ANCHOR)
    listbox.destroy()
    T.image_create(tk.INSERT, image=Images[fn])
tk.Button(root, text="Add Image", font=('Verdana',8), 
command=add_img).place(x=690,y=0)
T = tk.Text(root, width=65, height=17, padx=10, pady=10, font=('Verdana', 
14), wrap='word')
T.place(x=0, y=50)
root.mainloop()