zoukankan      html  css  js  c++  java
  • python对象的生命周期

    引言

    碰到以下问题:

    代码1:

    from Tkinter import *
    root = Tk()
    photo = PhotoImage(file=r'E:workspacepython111.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:workspacepython111.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:workspacepython111.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__函数,如下:

  • 相关阅读:
    Html5 冒泡排序演示
    Html5 Json应用
    Html5 和 CSS的简单应用
    Html5 布局方式
    Html5 绘制五星红旗
    Html5 绘制旋转的太极图
    Html5绘制时钟
    Html5 实现灯笼绘制
    "电量信息"组件:<battery> —— 快应用组件库H-UI
    "系统音量"组件:<volume> —— 快应用组件库H-UI
  • 原文地址:https://www.cnblogs.com/Tommy-Yu/p/4181606.html
Copyright © 2011-2022 走看看