如何使用 Tkinter 調整影像大小?


要使用Tkinter 和其他 Python 包處理影像,我們通常使用 Python 中的Pillow 包(或 PIL)。它提供了一種載入、處理、操作、轉換以及幫助調整影像大小的方法。可以使用命令 pip install Pillow安裝該包。安裝完包後,我們可以使用'from PIL import Image, ImageTk'命令匯入它。

要使用 PIL 包調整影像大小,我們必須遵循以下步驟:

  • 在本地機器上安裝Pillow 包或PIL

  • 使用Open(image_location)方法開啟影像。

  • 使用resize((w,h), Image.ANTIALIAS)方法調整給定影像的大小,其中ANTIALIAS 會去除影像周圍的結構填充。

  • 使用 Canvas 的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= (Image.open("download.png"))

#Resize the Image using resize method
resized_image= img.resize((300,205), Image.ANTIALIAS)
new_image= ImageTk.PhotoImage(resized_image)

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

win.mainloop()

輸出

執行以上程式碼將顯示一個視窗,該視窗將在畫布上顯示調整大小後的影像。

更新於: 2023年9月14日

37K+ 瀏覽量

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告