按钮上的图像
我希望下面这两个脚本的输出结果是一样的。
但是,当我运行脚本 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()
脚本 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()
5 个回答
1
logo = PhotoImage(file = 'mine32.gif')
small_logo = logo.subsample(5, 5)
self.b.config(image = small_logo , compound = LEFT )
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。
1
这个是有效的
x1=Button(root)
photo=PhotoImage(file="Re.png")
x1.config(image=photo,width="40",height="40",activebackground="black"
,bg="black", bd=0,command=sil)
x1.place(relx=1,x=5, y=-5, anchor=NE)
但是这个没什么用
def r():
x1=Button(root)
photo=PhotoImage(file="Re.png")
x1.config(image=photo,width="40",height="40",activebackground="black",
bg="black", bd=0,command=sil)
x1.place(relx=1,x=5, y=-5, anchor=NE)
r()
37
这个图片对象只有一个本地变量在引用。当__init__
这个函数结束时,本地变量就会被垃圾回收,所以这个图片就被销毁了。在第二个例子中,因为图片是在全局范围内创建的,所以它一直存在,不会被回收。
为了避免这个问题,可以保存对图片的引用。比如,不要用photo
,而是用self.photo
。