只要声明图像在哪里都没有关系,只要
如果您在main()
方法中定义图片,则必须制作它global
class MyCustomWindow(Tkinter.Frame):
def __init__(self, parent):
Tkinter.Frame.__init__(self, parent)
Tkinter.Label(self, image=image).pack()
self.pack(side='top')
def main():
root = Tkinter.Tk()
global image # make image kNown in global scope
image = Tkinter.PhotoImage(file='image.gif')
MyCustomWindow(root)
root.mainloop()
if __name__ == "__main__":
main()
或者,您可以main()
完全删除方法,使其自动成为全局方法:
class MyCustomWindow(Tkinter.Frame):
# same as above
root = Tkinter.Tk()
image = Tkinter.PhotoImage(file='image.gif')
MyCustomWindow(root)
root.mainloop()
或者,在您的__init__
方法中声明图像,但请确保使用self
关键字将其绑定到您的Frame
对象,以便在__init__
完成操作时不会对其进行垃圾回收:
class MyCustomWindow(Tkinter.Frame):
def __init__(self, parent):
Tkinter.Frame.__init__(self, parent)
self.image = Tkinter.PhotoImage(file='image.gif')
Tkinter.Label(self, image=self.image).pack()
self.pack(side='top')
def main():
# same as above, but without creating the image