无法将图像与tkinter标签关联
我正在尝试在tkinter的图形界面中显示一张图片,使用的是tkinter.Label()这个组件。这个过程看起来简单明了,但我的代码却不管用!
代码:
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
,就没有编译错误了,但图形界面就是不显示任何图片!
有没有人能帮我找出问题出在哪里?
5 个回答
-1
试试下面的代码,我用这个方法解决了同样的错误:
window=Tk()
c=Canvas(window,height=2000,width=2000)
p=PhotoImage(file='flower1.gif',master = c)
c.create_image(500,500,image=p)
0
重启内核可以解决错误 "TclError: image "pyimage9" doesn't exist"。
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()
这会让我收到一个 运行时错误:创建图片太早。
不过你提到的错误是 image pyimage9
不存在,这就有点奇怪了,因为在代码开头你已经把 filename
设置为 'AP_icon.gif',所以你可能会想,应该会出现不同的错误。我不太明白 pyimage9
是从哪里来的。这让我觉得你可能在某个地方搞错了文件名?另外,你还需要把 root = tk.Tk()
移到导入语句的上面。
1
在你调用任何其他tkinter功能之前,必须先创建根部件(root widget)。所以,把root
的创建放在图像创建之前。
2
这个问题发生在我们尝试在Ipython中运行上面的代码时。解决这个问题的方法是修改这一行
root = tk.Tk() to
root = tk.Toplevel()