此代码有效:
import tkinter root = tkinter.Tk() canvas = tkinter.Canvas(root) canvas.grid(row = 0, column = 0) photo = tkinter.PhotoImage(file = './test.gif') canvas.create_image(0, 0, image=photo) root.mainloop()
它显示了图像。
现在,此代码可以编译,但不会显示图像,我也不知道为什么,因为它是同一类的代码:
import tkinter class Test: def __init__(self, master): canvas = tkinter.Canvas(master) canvas.grid(row = 0, column = 0) photo = tkinter.PhotoImage(file = './test.gif') canvas.create_image(0, 0, image=photo) root = tkinter.Tk() test = Test(root) root.mainloop()
该变量photo是一个局部变量,在实例化类后会获取垃圾。保存对照片的引用,例如:
self.photo = tkinter.PhotoImage(...)