Python Tkinter PhotoImage

Chr*_*ung 4 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)
    root.mainlopp()

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

我的问题是:我应该在哪里宣布Myimage我在课堂上使用的照片mycustomwindow

如果我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()
Run Code Online (Sandbox Code Playgroud)

如果我把Myimage=tk.PhotoImage(data='....')在功能main()这样的,它说,它无法找到图像Myimageclass mycustomwindow.

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()
Run Code Online (Sandbox Code Playgroud)

我的代码结构有什么严重错误吗?我应该在哪里声明Myimage它可以用于class mycustomwindow

tob*_*s_k 8

只要声明图像,它就没有多大关系

  1. 初始化创建它Tk()(第一种方法中的问题)
  2. 当您使用它时,图像处于可变范围内(第二种方法中的问题)
  3. 图像对象不会被垃圾收集(另一个常见的 陷阱)

如果您在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()
Run Code Online (Sandbox Code Playgroud)

或者,您可以main()完全放弃您的方法,使其自动全局:

class MyCustomWindow(Tkinter.Frame):
    # same as above

root = Tkinter.Tk()
image = Tkinter.PhotoImage(file='image.gif')
MyCustomWindow(root)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)

或者,在__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
Run Code Online (Sandbox Code Playgroud)