如何在畫布上用 Tkinter 開啟 PIL 影像?


Pillow 軟體包(或 PIL)極大地幫助處理和載入 Python 專案中的影像。它是一個免費的開源庫,可用在 Python 中,可增加載入、處理和處理不同格式影像的支援。

為了在 Tkinter 畫布中開啟影像,我們必須首先使用 from PIL import Image, ImageTk 命令匯入庫。為了在我們的 Tkinter 應用程式中顯示影像,我們可以透過在 create_image(x,y,image) 方法中指定影像檔案來使用畫布小部件。

示例

#Import the required Libraries
from tkinter import *
from PIL import Image,ImageTk

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

#Set the geometry of tkinter frame
win.geometry("750x270")

#Create a canvas
canvas= Canvas(win, width= 600, height= 400)
canvas.pack()

#Load an image in the script
img= ImageTk.PhotoImage(Image.open("download.png"))

#Add image to the Canvas Items
canvas.create_image(10,10,anchor=NW,image=img)

win.mainloop()

輸出

執行上述程式碼將在畫布小部件內顯示一個帶有影像的視窗。

更新於: 2021-05-04

超過 5K 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.