繁体   English   中英

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

[英]How to place a jpeg into tkinter (python3.4)?

我正在尝试制作一个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

提前致谢

你需要添加2行如下(我评论了相关的行)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM