图像上的一个按钮 [英] Image on a button
问题描述
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()
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()
我期望两个以上的脚本的相同的输出。但我没有得到的图像上的按钮,当我执行的第一个程序。然而,第二个效果很好。
I expect the same output for both of the above scripts. But I don't get the image on the button when I execute the first program. However, the second one works well.
推荐答案
对图像对象的引用仅是一个局部变量。当 __ __的init
退出,局部变量是收集,因此图像没有被销毁垃圾。在第二个例子中,因为图像是在全球范围内创造了它永不熄灭的范围,因此是永远不会被垃圾收集。
The only reference to the image object is a local variable. When __init__
exits, the local variable is garbage collected so the image no is destroyed. In the second example, because the image is created at the global level it never goes out of scope and is therefore never garbage collected.
要解决此问题,保存到图片的引用。例如,而不是照片
使用 self.photo
To work around this, save a reference to the image. For example, instead of photo
use self.photo
这篇关于图像上的一个按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!