python对象的生命周期


引言

碰到以下问题:

代码1:

from Tkinter import *
root = Tk()
photo = PhotoImage(file=r'E:\workspace\python\111.gif')
Label(root,image=photo).grid()
root.mainloop()

这个能正常显示图片。而下面的代码却不能:

 

代码2:

from Tkinter import *
root = Tk()

def _test_img():
    win= Toplevel(root)
    photo = PhotoImage(file=r'E:\workspace\python\111.gif')
    Label(win,image=photo).pack()
    
Button(root,text="test",command=_test_img).grid()

root.mainloop()

 

怀疑是生命周期的问题,引入1/0错误:

from Tkinter import *
root = Tk()

def _test_img():
    win= Toplevel(root)
    photo = PhotoImage(file=r'E:\workspace\python\111.gif')
    Label(win,image=photo,bg='blue').pack()
    1/0
    
Button(root,text="test",command=_test_img).grid()

root.mainloop()

这样就能正常显示图片,因python的回收机制被错误中断了。

或者将photo变成全局变量也能达到同样的效果。

 

这里很奇怪,win/Label在函数执行完没有销毁,而photo貌似却销毁了。

 

python何时销毁一个对象?

关于垃圾回收机制,可以参考下这里

问题来了:神马叫做引用?

root->win->Label--?-->photo

为何最后一环断掉了?看下PhotoImage的__init__函数,如下:

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM