如何将jpeg放入tkinter(python3.4)?

时间:2016-06-27 19:22:12

标签: python python-3.x tkinter

我正在尝试制作一个tkinter代码,可以生成一个带有图像的窗口。这个区域一直给我一个错误:

window=tk.Tk()
window.geometry('1100x900')
window.title('Hello World')
lab1= tk.Label(window, text='Input the desired delay time')
btn=tk.Button(window, text='Go to new window', bg='Blue', command=NewTab)
btn2=tk.Button(window, text='Leave', bg='Red', command=close)
imgset=ImageTk.PhotoImage(Image.open(imgpath))
img = tk.Label(window, image=imgset)
img.pack()

lab1.pack()
btn.pack()
btn2.pack()

window.mainloop()

其中imagepath是my pictures文件夹中图片的路径

这是我一直得到的错误

Traceback (most recent call last):
  File "C:\PythonScripts\trunk\Personal\PythonWindow_ForTiming.py", line 49, in <module>
    img = tk.Label(window, image=imgset)
  File "C:\Python34\lib\tkinter\__init__.py", line 2604, in __init__
    Widget.__init__(self, master, 'label', cnf, kw)
  File "C:\Python34\lib\tkinter\__init__.py", line 2122, in __init__
    (widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "pyimage1" doesn't exist

我做错了什么?你可以请一下评论来帮助我理解,我只是在学习tkinter

提前致谢

1 个答案:

答案 0 :(得分:0)

您需要添加以下两行(我对相关行进行了评论)

imgset=Image.open(imgpath)
# Convert imgset to a Tkinter-compatible image object
photo = ImageTk.PhotoImage(imgset) 
img = tk.Label(window, image=photo)
# Keep a reference to the image
img.image = photo 
img.pack()

小学提示:您可以将img重命名为更好地反映Label()实例的内容(以避免最终的混淆),例如label

您可能有兴趣阅读The Tkinter PhotoImage Class