这是我目前拥有的代码格式:
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()我的问题是:我应该在哪里声明我在mycustomwindow类中使用的照片Myimage
如果我像下面这样把Myimage=tk.PhotoImage(data='....')放在root=tk.Tk()之前,它会给出too early to create image错误,因为我们不能在根窗口之前创建图像。
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()中,它会说在class 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()我的代码结构有什么严重的错误吗?为了在class mycustomwindow中使用,我应该在哪里声明Myimage
发布于 2013-07-20 18:24:06
在哪里声明图像并不重要,只要
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()或者,在__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 imagehttps://stackoverflow.com/questions/17760871
复制相似问题