如何向 Python Tkinter 視窗插入 JPEG 影像?


Python 提供了**Pillow** (PIL) 包,可在 tkinter 應用程式中支援、處理和顯示影像。Tkinter 應用程式通常支援影像檔案,例如 ppm、png 和 gif。

假設我們要在應用程式中嵌入和顯示 JPEG 或 JPG 影像。

Tkinter Label 小部件通常用於在視窗上顯示文字或影像,因此透過傳遞 img 值,我們可以在視窗中顯示 JPEG 影像。

示例

#Import required libraries
from tkinter import *
from PIL import ImageTk, Image

#Create an instance of tkinter window
win =Tk()

#Define the geometry of the window
win.geometry("650x400")

#Initialize the file name in a variable
path = "file.jpg"

#Create an object of tkinter ImageTk
img = ImageTk.PhotoImage(Image.open(path))

#Create a Label Widget to display the text or Image
label = tk.Label(win, image = img)
label.pack(fill = "both", expand = "yes")

win.mainloop()

輸出

該程式碼將顯示作為 Label 小部件中的影像值傳遞的 JPEG 影像。

更新於:2021-03-27

3K+ 次瀏覽

開啟你的 職業

完成課程以獲得認證

開始
廣告