简体   繁体   中英

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. 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

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

Thanks in advance

You need to add 2 lines as following (I commented the lines in question)

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

You may be interested in reading The Tkinter PhotoImage Class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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