【问题标题】:Tkinter text-widget insertion of imagesTkinter 文本小部件插入图像
【发布时间】:2019-10-19 08:42:32
【问题描述】:

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

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 选择时添加不同的图像。

感谢您的帮助。

【问题讨论】:

  • 创建第二个图像与创建第一个图像没有什么不同。目前还不清楚你在问什么。此外,您提到了一个列表框,但您的代码没有列表框。
  • 我的问题是:是否有必要为所有可用图像声明变量。因为当我对第二张图像使用相同的变量时,第一个被删除。是否可以使用 glob.glob('*.gif') 创建一个包含所有图像文件的列表框并创建该图像。
  • 是的,我可以创建另一个变量 img... 并声明它。有没有办法让我只更改文件。 img = tk.PhotoImage(文件=变量)。我没有使用上述示例的列表框,但有可能吗?

标签: python-3.x tkinter


【解决方案1】:

我用字典来解决这个问题。

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 2014-03-18
    • 2017-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多