0

我正在尝试使用 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没有它的 parentroot时,不会发生编译错误,但 GUI 不显示任何图像!

谁能确定可能是什么问题?

4

5 回答 5

1

当我们尝试在 Ipython 中运行上述代码时,就会出现这个问题。并且可以通过换行来解决

root = tk.Tk() to

root = tk.Toplevel()
于 2014-10-24T23:08:19.350 回答
0

在调用任何其他 tkinter 函数之前,您需要创建根小部件。将创建移动到创建root图像之前。

于 2014-08-23T12:14:23.503 回答
0

我用来在 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()导入下的顶部。

于 2014-08-23T20:09:34.370 回答
0

重新启动内核以消除错误“TclError:图像“pyimage9”不存在”

于 2019-12-01T08:16:01.730 回答
-1

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

window=Tk()
c=Canvas(window,height=2000,width=2000)
p=PhotoImage(file='flower1.gif',master = c)
c.create_image(500,500,image=p)
于 2019-10-13T00:56:47.347 回答