如何在 Tkinter 中使用 Pillow 來顯示圖片?


Python 提供 Pillow Package (PIL) 來在應用程式中處理和載入圖片。可以使用內建的 Image.open("image location") 方法來載入圖片。此外,我們可以使用標籤控制元件在視窗中顯示圖片。

範例

#Import tkinter library
from tkinter import *
from PIL import Image,ImageTk
#Create an instance of tkinter frame
win = Tk()
#Set the geometry
win.geometry("750x550")
#Load the image
img= Image.open("tutorialspoint.jpg")
#Convert To photoimage
tkimage= ImageTk.PhotoImage(img)
#Display the Image
label=Label(win,image=tkimage)
label.pack()
win.mainloop()

輸出

執行上述程式碼將在視窗中顯示一張圖片。

在執行程式碼前,確保你的圖片位於與專案相同的目錄中,或提供圖片位置的絕對路徑。

更新於: 2021-04-15

1 千次瀏覽

開啟你的職業生涯

透過學習課程獲取認證

開始學習
廣告