问题:
- 利用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中图形对象被垃圾回收了,图形就会完全丢失,必须保存显式的图形对象引用
- 图像对象
pic
为Demo
类中的局部对象,Demo
实例化后pic
对象即被垃圾回收,再调用其mainloop()
方法时,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()