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

如何解决Tkinter Treeview无法显示MySQL数据库图片的问题

解决Tkinter Treeview无法显示MySQL存储图片的问题

问题分析与修复点

  • 第一条记录被跳过:代码中先执行了record = c.fetchone(),会取出查询结果的第一条数据,后续for record in c只能遍历剩余记录,导致第一条数据的图片和ID都无法显示,直接删除这行即可。
  • 图片引用被垃圾回收:Tkinter的PhotoImage对象如果没有持续引用,会被Python垃圾回收机制清理,导致图片不显示。不要用单个全局变量img,改用列表存储所有图片的引用,确保每个图片对象都能被持有。
  • 字段索引需确认:要保证record[11]确实对应数据库中存储图片的字段,避免因字段顺序错误取到非图片数据。

修正后的代码

try:
    # 用列表存储所有图片引用,防止被垃圾回收
    global img_list
    img_list = []
    select_query = "select * from tblproduct"
    c.execute(select_query)
    # 遍历所有查询结果,不再跳过第一条
    for record in c:
        prod_img_data = record[11]
        if prod_img_data:  # 检查是否存在有效图片数据
            prod_img = Image.open(io.BytesIO(prod_img_data))
            prod_img.thumbnail((50, 50))
            img = ImageTk.PhotoImage(prod_img)
            img_list.append(img)  # 保存图片引用
            product_view.insert(parent="", index="end", image=img, values=(record[0]))
        else:
            # 无图片时的兜底处理,可根据需求调整
            product_view.insert(parent="", index="end", values=(record[0]))
except mysql.connector.Error as error:
    messagebox.showerror(title='Error', message=str(error))

额外注意事项

  • 确保Treeview组件已正确配置列,比如若希望图片显示在ID之后,创建Treeview时可设置product_view = ttk.Treeview(root, columns=('id', 'image'), show='headings'),后续再将对应列标题修改为“产品图片”。
  • 可单独提取record[11]的数据保存为图片文件,验证数据库中存储的图片数据是否完整未损坏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 10:42:40