Python Tkinter照片图像
这是我目前拥有的代码格式:Python Tkinter照片图像,python,class,tkinter,Python,Class,Tkinter,这是我目前拥有的代码格式: import Tkinter as tk class mycustomwidow: def __init__(self,parent,......) ...... ...... tk.Label(parent,image=Myimage) tk.pack(side='top') def main(): root=tk.Tk() mycustomwindow(root)
import Tkinter as tk
class mycustomwidow:
def __init__(self,parent,......)
......
......
tk.Label(parent,image=Myimage)
tk.pack(side='top')
def main():
root=tk.Tk()
mycustomwindow(root)
root.mainlopp()
if __name__ == '__main__':
main()
我的问题是:我应该在哪里声明我在类中使用的照片Myimage
如果我将Myimage=tk.PhotoImage(data='..')
放在root=tk.tk()
之前,如下图所示,则会出现创建图像太早的错误,因为我们无法在根窗口之前创建图像
import Tkinter as tk
Myimage=tk.PhotoImage(data='....')
class mycustomwidow:
def __init__(self,parent,......)
......
......
tk.Label(parent,image=Myimage)
tk.pack(side='top')
def main():
root=tk.Tk()
mycustomwindow(root)
root.mainlopp()
if __name__ == '__main__':
main()
如果我像这样将Myimage=tk.PhotoImage(data='..')
放入函数main()
中,它表示在类mycustomwindow
中找不到图像Myimage
import Tkinter as tk
class mycustomwidow:
def __init__(self,parent,......)
......
......
tk.Label(parent,image=Myimage)
tk.pack(side='top')
def main():
root=tk.Tk()
Myimage=tk.PhotoImage(data='....')
mycustomwindow(root)
root.mainlopp()
if __name__ == '__main__':
main()
我的代码结构有什么严重错误吗?我应该在哪里声明Myimage
,以便在类mycustomwindow
中使用它?在哪里声明图像无关紧要,只要
在初始化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 above
root = Tkinter.Tk()
image = Tkinter.PhotoImage(file='image.gif')
MyCustomWindow(root)
root.mainloop()
或者,在\uuuuu init\uuuu
方法中声明图像,但请确保使用self
关键字将其绑定到框架
对象,以便在\uuuuuu init\uuu
完成时不会对其进行垃圾收集:
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