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

Python+Tkinter类中GUI图片异常:进入mainloop后画布清空

问题原因

这是因为ImageTk.PhotoImage对象会被Python垃圾回收机制回收——在__init__方法里,img是局部变量,当__init__执行完毕后,该变量会被销毁,对应的图片对象也会被回收,因此进入mainloop()后Canvas上的图片会消失。另外,你创建的canvas同样是局部变量,存在被回收的风险。

解决方案

将img和canvas保存为类的实例属性(添加self.前缀),让它们的生命周期与Gui实例保持一致,避免被垃圾回收。

修改后的代码

import tkinter as tk
from PIL import Image, ImageTk
import time

class Gui():
    
    def __init__(self, window):       
        File = "/home/pi/Rainer/Graphic/Bahn01.png"
        self.img = self.load_image(File, 0.5)  # 保存为实例属性
       
        self.canvas = tk.Canvas(window, bg='white')  # 保存为实例属性
        self.canvas.place(x=10, y=10, width=300, height=400)
        self.canvas.create_image(0, 0, image=self.img, anchor="nw")
        window.update()

    def load_image(self, File, Zoom):
        img = Image.open(File)
        resized_image = img.resize((int(600 * Zoom), int(800 * Zoom)), Image.Resampling.LANCZOS)
        return ImageTk.PhotoImage(resized_image)

def main():  
    
    root = tk.Tk()
    root.geometry("620x420+320+20")
        
    App = Gui(root)
    
    time.sleep(3)

    root.mainloop()


if __name__ == '__main__':
    main()

关键说明

  • 使用self.img替代局部变量img,将图片对象绑定到Gui实例上,只要App实例存在,图片就不会被回收。
  • 将canvas改为self.canvas,保留对Canvas控件的引用,避免出现意外的控件回收问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 05:15:07