簡體   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