【问题标题】:Python Tkinter PhotoImagePython Tkinter PhotoImage
【发布时间】:2013-07-19 14:40:50
【问题描述】:

这是我目前拥有的代码格式:

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 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()

如果我像这样将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()

我的代码结构有什么严重问题吗?我应该在哪里声明 Myimage 以便它可以在 class mycustomwindow 中使用?

【问题讨论】:

    标签: python class tkinter


    【解决方案1】:

    在哪里声明图像并不重要,只要

    1. 初始化Tk() 之后创建它(第一种方法中的问题)
    2. 图像在您使用时在变量范围内(第二种方法中的问题)
    3. 图像对象没有被垃圾回收(另一个commonpitfall

    如果您在 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-22
      • 1970-01-01
      • 2015-07-23
      • 2023-04-02
      • 1970-01-01
      相关资源
      最近更新 更多