我正在尝试使用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不显示任何图像!
任何人都可以确定可能出现的问题吗?
答案 0 :(得分:1)
当我们尝试在Ipython中运行上面的代码时会发生此问题。它可以通过更改行来解决
root = tk.Tk() to
root = tk.Toplevel()
答案 1 :(得分:0)
在调用任何其他tkinter函数之前,您需要创建根小部件。将root
的创建移动到创建图像之前。
答案 2 :(得分: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()
移到导入下的顶部。
答案 3 :(得分:0)
重新启动内核以消除错误“ TclError:图像“ pyimage9”不存在”
答案 4 :(得分:-1)
请尝试以下代码,以纠正相同的错误:
window=Tk()
c=Canvas(window,height=2000,width=2000)
p=PhotoImage(file='flower1.gif',master = c)
c.create_image(500,500,image=p)