Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การปรับขนาดภาพด้วย ImageTk.PhotoImage ใน Tkinter


ไลบรารี PIL หรือ Pillow ใน Python ใช้ประมวลผลภาพในแอปพลิเคชัน Tkinter ใช้ Pillow เปิดภาพ ปรับขนาด และแสดงในหน้าต่าง ปรับขนาดภาพใช้เมธอด image_resize((width, height) **options) ภาพที่ปรับขนาดแล้วสามารถประมวลผลและแสดงผ่าน label widget

ตัวอย่าง

ตัวอย่างเปิดภาพและปรับขนาดแสดงในหน้าต่างผ่าน label widget

# 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)) 
# Convert the image in TkImage 
my_img=ImageTk.PhotoImage(img) 
# Display the image with label 
label=Label(win, image=my_img) 
label.pack() 
win.mainloop()

ผลลัพธ์

รันโค้ด จะแสดงภาพที่ปรับขนาดแล้วในหน้าต่าง

การปรับขนาดภาพด้วย ImageTk.PhotoImage ใน Tkinter