如果在函数中创建Tkinter图像,为什么不显示? [英] Why does Tkinter image not show up if created in a function?
本文介绍了如果在函数中创建Tkinter图像,为什么不显示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
此代码有效:
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()
它向我显示了图像。
现在,这段代码编译但它没有显示我的图像,我不知道为什么,因为它是相同的代码,在课堂上:
Now, this code compiles but it doesn't show me the image, and I don't know why, because it's the same code, in a class:
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
是一个局部变量在实例化类之后获取垃圾。保存对照片的引用,例如:
The variable photo
is a local variable which gets garbage collected after the class is instantiated. Save a reference to the photo, for example:
self.photo = tkinter.PhotoImage(...)
如果您在tkinter图片无法显示上进行Google搜索,则第一个结果为:
If you do a Google search on "tkinter image doesn't display", the first result is this:
http ://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm
这篇关于如果在函数中创建Tkinter图像,为什么不显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文