如果在函数中创建,为什么 Tkinter 图像不显示? [英] Why does Tkinter image not show up if created in a function?

查看:31
本文介绍了如果在函数中创建,为什么 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(...)

如果您在 Google 上搜索tkinter 图像不显示",第一个结果是:

If you do a Google search on "tkinter image doesn't display", the first result is this:

为什么我的 Tkinter 图像没有出现?(常见问题解答目前过时)

Why do my Tkinter images not appear? (The FAQ answer is currently not outdated)

这篇关于如果在函数中创建,为什么 Tkinter 图像不显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆