a2005147 发表于 2015-12-3 10:58:27

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__函数,如下:
  
页: [1]
查看完整版本: python对象的生命周期