我應該如何同時使用 PIL 和 Tkinter?


Python 中的 PIL 或 Pillow 包提供了一種在程式中處理影像的方法。我們可以開啟一張圖片,對圖片進行不同的處理,並且可以用它來視覺化資料。若要在 Tkinter 中使用 PIL 包,你必須在環境中安裝 Python Pillow 庫。

要安裝 Pillow,只需輸入pip install pillow。一旦安裝成功,你就可以將模組匯入到你的專案中,並用於進一步實現。

示例

在這個示例中,我們使用 Python Pillow 包在畫布元件中顯示了一幅影像。

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

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

# Set the size of the window
win.geometry("700x350")

# Create a canvas widget
canvas=Canvas(win, width=700, height=350)
canvas.pack()

# Load the image
img=ImageTk.PhotoImage(file="opera.jpg")

# Add the image in the canvas
canvas.create_image(350, 200, image=img, anchor="center")

win.mainloop()

輸出

如果我們執行上面的程式碼,它將在視窗中顯示一張圖片。

更新於: 05-Aug-2021

3K+ 瀏覽量

職業起步

完成課程後獲得認證

開始學習
廣告