【发布时间】:2014-08-23 09:20:55
【问题描述】:
我正在尝试使用 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 不显示任何图像!
谁能确定可能是什么问题?
【问题讨论】:
-
如果我交换
root = tk.Tk()和tkim = ImageTk...语句的顺序,您的代码对我有效。 -
谢谢。但我尝试交换语句,但同样的错误再次重复。还有其他可能的原因吗?
-
你确定上面的代码给出了你所说的错误吗?通常内部图像从零开始编号,但您声称错误提及“pyimage9”,即使您的代码尝试创建单个图像。
-
很高兴你问。事实上,编号对我来说是从 1 开始的。但是当我再次运行时(我在 ubuntu 12.04 中使用 ipython),数字会更新为 2,3 等。我复制的错误是我第 9 次尝试运行类似的代码。
标签: python user-interface tkinter photoimage