You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter Text组件插入图片问题:通过ListBox选择添加多张图片

实现通过ListBox选择并向Text组件添加多张图片

我来帮你搞定这个问题!原来的代码里因为只用了单个全局变量存储图片对象,不仅每次选新图会覆盖旧的,还容易被Python的垃圾回收机制清理导致图片显示异常。下面是修改后的完整实现,完美支持通过ListBox选择不同图片并添加多张到Text组件中:

import tkinter as tk

root = tk.Tk()
root.geometry('800x520+0+0')

# 用来保存图片引用,防止被垃圾回收机制清理
image_references = []
# 可选图片路径列表,替换成你自己的图片路径
available_images = ['quiz.gif', 'image2.gif', 'image3.gif']

def add_img():
    # 获取ListBox中选中的图片项
    selected_indices = listbox.curselection()
    if not selected_indices:
        return
    selected_img_path = available_images[selected_indices[0]]
    # 创建图片对象并保存引用
    img = tk.PhotoImage(file=selected_img_path)
    image_references.append(img)
    # 将图片插入到Text组件的当前光标位置
    T.image_create(tk.INSERT, image=img)

# 创建Text组件
T = tk.Text(root, width=65, height=17, padx=10, pady=10, font=('Verdana', 14), wrap='word')
T.place(x=0, y=0)

# 创建ListBox用于选择图片
listbox = tk.Listbox(root, font=('Verdana', 10), width=20, height=10)
listbox.place(x=690, y=30)
# 填充图片选项
for img_name in available_images:
    listbox.insert(tk.END, img_name)

# 创建添加图片按钮
tk.Button(root, text="Add Image", font=('Verdana',8), command=add_img).place(x=690, y=0)

root.mainloop()

关键改动说明:

  • 图片引用管理:新增image_references列表来存储所有添加的PhotoImage对象,这是因为tkinter的图片对象如果没有被持续引用,会被Python自动回收,导致Text里的图片消失。
  • ListBox选择功能:添加了ListBox组件展示可选的图片路径,你可以根据自己的实际图片修改available_images列表。
  • 多图添加逻辑:修改add_img函数,先获取ListBox选中的图片路径,创建对应的图片对象后插入到Text的当前光标位置,同时把图片对象存入引用列表,这样就能支持多次添加不同图片,不会覆盖之前的内容。

内容的提问来源于stack exchange,提问作者Ashutosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:18:41