Python tkinter中 图形 无法显示

问题:

  • 利用tkinter基于Frame创建类,在其中使用了 图形 对象。调用该类并执行主循环,窗口中无法显示使用的图像,代码如下:
from tkinter import *

class Demo(Frame):
    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        self.pack(expand=YES, fill=BOTH)
        
        pic = PhotoImage(file='pic.gif')
        width, height=pic.width(), pic.height()
        
        canv = Canvas(self, width=width, height=height, relief=RIDGE, bd=2)
        canv.pack(side=TOP, expand=YES, fill=BOTH)
        canv.create_image(0, 0, image=pic, anchor=NW)

if __name__ == '__main__':
    root = Tk()
    Demo(root).mainloop()

原因:

  • 和其他tkinter组件不同的是,Python中图形对象被垃圾回收了,图形就会完全丢失,必须保存显式的图形对象引用
  • 图像对象picDemo类中的局部对象,Demo实例化后pic对象即被垃圾回收,再调用其mainloop()方法时,pic对象已不存在

解决方案:

  • pic设置为类属性self.pic
class Demo(Frame):
    def __init__(self, parent=None):
        ...
        self.pic = pic
        canv.create_image(0, 0, image=self.pic, anchor=NW)

if __name__ == '__main__':
    root = Tk()
    Demo(root).mainloop()
  • 在主循环中创建全局图形对象
class Demo(Frame):
    def __init__(self, parent=None, pic=None):
        Frame.__init__(self, parent)
        self.pack(expand=YES, fill=BOTH)
        
        width, height=pic.width(), pic.height()
        canv = Canvas(self, width=width, height=height, relief=RIDGE, bd=2)
        canv.pack(side=TOP, expand=YES, fill=BOTH)
        
        canv.create_image(0, 0, image=pic, anchor=NW)

if __name__ == '__main__':
    root = Tk()
    pic = PhotoImage(file='pic.gif')
    Demo(root, pic).mainloop()

猜你喜欢

转载自blog.csdn.net/yangwenwu11514/article/details/85199891