无法将图像关联到tkinter标签



我试图使用tkinter. label()小部件将图像显示到tkinter GUI。这个过程看起来简单直接,但是这段代码不起作用!

代码:

import Tkinter as tk
import Image, ImageTk, sys
filename = 'AP_icon.gif'
im = Image.open(filename) # Image is loaded, because the im.show() works
tkim = ImageTk.PhotoImage(im)
root = tk.Tk()
label = tk.Label(root, image = tkim) # Here is the core problem (see text for explanation)
label.image = tkim # This is where we should keep the reference, right?
label.grid (row = 0, column = 0)
tk.Button(root, text = 'quit', command = lambda: sys.exit()).grid(row = 1, column = 1)
root.mainloop()

当我们执行这段代码时,它不能编译,给出一个错误:

TclError: image "pyimage9" doesn't exist

当我定义label没有其父root时,没有编译错误发生,但GUI不显示任何图像!

谁能确定是什么问题?

当我们试图在Ipython中运行上述代码时,就会出现这个问题。这可以通过改变

一行来解决
root = tk.Tk() to
root = tk.Toplevel()

您需要在调用任何其他tkinter函数之前创建根小部件。

root的创建移动到创建图像之前。

我用tkinter显示图像的一般方式是:

import Tkinter as tk
root = tk.Tk()
image1 = tk.PhotoImage(file = 'name of image.gif')
# If image is stored in the same place as the python code file,
# otherwise you can have the directory of the image file.
label = tk.Label(image = image1)
label.image = image1 # yes can keep a reference - good!
label.pack()
root.mainloop()

在上面的例子中,它是有效的,但是你要像这样:

import Tkinter as tk
image = tk.PhotoImage(file = 'DreamPizzas.gif') #here this is before root = tk.Tk()
root = tk.Tk()
# If image is stored in the same place as the python code file,
# otherwise you can have the directory of the image file.
label = tk.Label(image = image)
label.image = image
label.pack()
root.mainloop()

这给我一个runtime error: too early to create image.

但是你说你的错误是image pyimage9不存在,这很奇怪,因为在顶部你已经将filename设置为'AP_icon.gif',所以你会认为你得到一个不同的错误,因为我不知道pyimage9来自哪里。这让我认为,也许你得到的文件名不正确的地方?您还需要将root = tk.Tk()移动到顶部的imports

重新启动内核以消除错误"TclError: image "pyimage9"不存在"

尝试以下代码,因为我能够纠正相同的错误:

window=Tk()
c=Canvas(window,height=2000,width=2000)
p=PhotoImage(file='flower1.gif',master = c)
c.create_image(500,500,image=p)

最新更新