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