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

Python tkinter使用canvas渲染数据库图片调试正常运行不显示问题

问题根因
  • 该异常是Tkinter的PhotoImage对象垃圾回收逻辑导致的:Tkinter本身不会持有PhotoImage实例的引用,你代码中循环内创建的photoImage是局部变量,循环执行结束后变量超出作用域就会被Python垃圾回收器清理,对应的图片资源也会被释放,canvas就无法渲染对应的图片。
  • 调试时断点会暂停程序运行,此时photoImage还未被回收,因此可以正常显示图片。
修复方案

你只需要将每个PhotoImage实例存入一个和当前组件生命周期匹配的持久化容器中即可,比如给当前类新增一个列表属性存储所有图片实例:

count = 0
posx = 1
posy = 5
# 新增列表存储PhotoImage实例,避免被回收
self.photo_list = []
for imagem in self.imagens:

    img1 = Image.open(imagem[2])
    img1 = img1.resize((200, 200), Image.ANTIALIAS)
    photoImage = ImageTk.PhotoImage(img1)
    # 把实例加入列表保留引用
    self.photo_list.append(photoImage)

    self.canvas.create_image(posy, posx, anchor=NW, image=photoImage)

    count = count + 1
    if count == 9:
        break

    if count == 0 or count == 3 or count == 6:
        posy = 5
    elif count == 1 or count == 4 or count == 7:
        posy = 210
    elif count == 2 or count == 5 or count == 8:
        posy = 415

    if count > 2 and count < 5:
        posx = 205
    elif count > 5 and count < 8:
        posx = 410
补充说明
  • 如果你使用的Pillow版本≥9.1.0,Image.ANTIALIAS已经被废弃,替换为Image.Resampling.LANCZOS即可获得相同的缩放效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 23:15:06