只要声明图像在哪里都没有关系,只要
- 您 在 初始化 后 创建它
Tk()
(第一种方法中的问题) - 使用图像时图像 在可变范围内 (第二种方法中的问题)
- 图像对象不会 被垃圾收集 (另一个常见 陷阱)
如果您在
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 aboveroot = 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



