您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python Tkinter PhotoImage

Python Tkinter PhotoImage

只要声明图像在哪里都没有关系,只要

如果您在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
python 2022/1/1 18:49:49 有355人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶