使用 PIL 在 Tkinter Canvas 小元件中嵌入圖片
Pillow 庫在 Python 中包含所有基本的影像處理功能。它是一個開源庫,可在 Python 中使用,可載入、處理和操作不同格式的影像。
我們透過一個簡單的示例,看看如何使用枕頭包 (PIL) 在 Tkinter 畫布中嵌入圖片。按照以下步驟操作 −
步驟 −
- 匯入所需的庫並建立 Tkinter 框架的例項。
from tkinter import * from PIL import Image, ImageTk
使用 root.geometry 方法設定框架的大小。
接下來,使用 canvas() 函式建立一個畫布小元件,並設定其高度和寬度。
使用 Image.open() 開啟圖片,然後使用 ImageTk.PhotoImage()將其轉換為 PIL 圖片。將 PIL 圖片儲存在變數 “img” 中。
接下來,使用 canvas.create_image()將 PIL 圖片新增到畫布。
最後,執行應用程式視窗的 mainloop。
示例
# Import the required Libraries from tkinter import * from PIL import Image, ImageTk # Create an instance of tkinter frame root = Tk() # Set the geometry of tkinter frame root.geometry("700x450") # Create a canvas widget canvas= Canvas(root, width=600, height=400) canvas.pack() # Load an image img=ImageTk.PhotoImage(Image.open("camels.jpg")) # Add image to the Canvas Items canvas.create_image(250, 250, anchor=CENTER, image=img) root.mainloop()
輸出
當您執行該程式碼時,它將產生以下輸出視窗 −
廣告