按钮上的图像 [英] Image on a button
问题描述
我希望以下两个脚本的输出相同.
I expect the same output for both of the scripts below.
但是当我执行脚本 1 时,我没有在按钮上看到图像.但是,脚本 2 运行良好.
But I don't get the image on the button when I execute Script 1. However, Script 2 works well.
脚本 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()
脚本 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()
推荐答案
对图像对象的唯一引用是局部变量.当 __init__
退出时,局部变量被垃圾回收,因此图像被销毁.在第二个示例中,因为图像是在全局级别创建的,所以它永远不会超出范围,因此永远不会被垃圾收集.
The only reference to the image object is a local variable. When __init__
exits, the local variable is garbage collected so the image 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
代替 photo
.
To work around this, save a reference to the image. For example, instead of photo
use self.photo
.
这篇关于按钮上的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!