使用Tkinter透過ImageTk.PhotoImage縮放影像


Tkinter應用程式中,PIL或Pillow庫用於處理影像。我們可以使用Pillow來開啟影像,調整它們的大小並在視窗中顯示。若要調整影像的大小,我們可以使用image_resize((width, height) **options)方法。調整大小的影像之後可以透過標籤小部件進行處理和顯示。

示例

我們看一下一個示例,其中我們將開啟一張影像並調整其大小以便透過標籤小部件在視窗中顯示。

# 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 tkinter window
win.geometry("700x350")

# Load the image
image=Image.open('download.png')

# Resize the image in the given (width, height)
img=image.resize((450, 350))

# Conver the image in TkImage
my_img=ImageTk.PhotoImage(img)

# Display the image with label
label=Label(win, image=my_img)
label.pack()

win.mainloop()

輸出

執行以上程式碼將在視窗中顯示調整大小的影像。

更新於:2021年8月6日

22K+ 瀏覽量

開始您的職業生涯

完成課程以獲得認證

開始
Advertisement
© . All rights reserved.