Python 如果在函数中创建,为什么 Tkinter 图像不显示?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16424091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:35:04  来源:igfitidea点击:

Why does Tkinter image not show up if created in a function?

pythonimagetkintertkinter-canvas

提问by thomas.winckell

This code works:

此代码有效:

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()

It shows me the image.

它向我展示了图像。

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()

采纳答案by Bryan Oakley

The variable photois a local variable which gets garbage collected after the class is instantiated. Save a reference to the photo, for example:

该变量photo是一个局部变量,它在类被实例化后被垃圾收集。保存对照片的引用,例如:

self.photo = tkinter.PhotoImage(...)

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

如果您对“tkinter 图像不显示”进行 Google 搜索,第一个结果是:

http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm

http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm

回答by Gabriel

Just add global photoas the first line inside the function.

只需添加global photo为函数内的第一行。