简体   繁体   English

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

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

I am trying to make a tkinter code that can generate a window with an image on it. 我正在尝试制作一个tkinter代码,可以生成一个带有图像的窗口。 This is the area that keeps giving me an error: 这个区域一直给我一个错误:

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()

where imagepath is a path to a picture in the my pictures folder 其中imagepath是my pictures文件夹中图片的路径

and this is the error I keep getting 这是我不断得到的错误

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

What am I doing incorrectly? 我做错了什么? Could you please include comments to help me understand, I am just learning about tkinter 你能否请一些评论来帮助我理解,我只是在学习tkinter

Thanks in advance 提前致谢

You need to add 2 lines as following (I commented the lines in question) 你需要添加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()

Elementary note: you may rename img to something that reflects the Label() instance better (to avoid an eventual confusion) such as label 小学提示:您可以将img重命名为更好地反映Label()实例的内容(以避免最终的混淆),例如label

You may be interested in reading The Tkinter PhotoImage Class 您可能有兴趣阅读The Tkinter PhotoImage Class

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

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