按钮上的图像

cod*_*der 19 python image tkinter button

我期望下面两个脚本的输出相同.

但是当我执行脚本1时,我没有在按钮上获得图像.但是,脚本2运行良好.

脚本1

from Tkinter import *
  class fe:
    def __init__(self,master):
      self.b=Button(master,justify = LEFT)
      photo=PhotoImage(file="mine32.gif")
      self.b.config(image=photo,width="10",height="10")
      self.b.pack(side=LEFT)
root = Tk()
front_end=fe(root)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)

脚本2

from Tkinter import *
root=Tk()
b=Button(root,justify = LEFT)
photo=PhotoImage(file="mine32.gif")
b.config(image=photo,width="10",height="10")
b.pack(side=LEFT)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)

Bry*_*ley 24

对图像对象的唯一引用是局部变量.当__init__退出时,局部变量是收集这样的图像没有被销毁垃圾.在第二个示例中,因为图像是在全局级别创建的,所以它永远不会超出范围,因此永远不会被垃圾回收.

要解决此问题,请保存对图像的引用.例如,而不是photo使用self.photo