Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/image/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么Tkinter图像在函数中创建时不显示?_Python_Image_Tkinter_Tkinter Canvas - Fatal编程技术网

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

Python 为什么Tkinter图像在函数中创建时不显示?,python,image,tkinter,tkinter-canvas,Python,Image,Tkinter,Tkinter Canvas,此代码适用于: 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

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(...)
如果您在谷歌搜索“tkinter图像不显示”,第一个结果是:


(常见问题解答目前尚未过时)

只需将
全局照片添加到函数的第一行即可

from tkinter import *
from PIL import ImageTk, Image

root = Tk()

def open_img():
    global img
    path = r"C:\.....\\"
    img = ImageTk.PhotoImage(Image.open(path))
    panel = Label(root, image=img)
    panel.pack(side="bottom", fill="both")
but1 = Button(root, text="click to get the image", command=open_img)
but1.pack()
root.mainloop() 
只需在img定义中添加global,它就会起作用


然后创建第二个
Test
实例,第一个实例将丢失其映像。恭喜你,勒芒,回答得很好!哇!他们认为这是特金特的错误吗?他们应该这么做。我发现了一张很旧的票,已经关闭了,没有修复程序:这个链接不能使用atm,除了使用“全球”还有其他方法吗?@TamasHegedus:我同意这是一个bug,但显然在(目前)近二十年后,没有人费心去修复它。我已经记不清有多少次我看到一个关于它的问题仍然弹出。它倒了。其要点是图像是通过引用传递的。如果引用是对局部变量的引用,则引用的内存将被重用,并且引用将过时。存储图像的变量应该与它出现的Tk gui对象在同一范围内(必须具有相同的生存期)。