ในการทำงานกับรูปภาพ Python Library มีแพ็คเกจ Pillow หรือ PIL ที่ช่วยให้แอปพลิเคชันนำเข้ารูปภาพและดำเนินการต่างๆ กับรูปภาพได้
ให้เราสมมติว่าเราต้องการปรับขนาดรูปภาพในหน้าต่างแบบไดนามิก ในกรณีเช่นนี้ เราต้องทำตามขั้นตอนเหล่านี้ -
-
เปิดรูปภาพในแอปพลิเคชัน Tkinter
-
สร้างวิดเจ็ต Canvas และใช้ create_image(**options) เพื่อวางภาพที่โหลดไว้บนผืนผ้าใบ
-
กำหนดฟังก์ชันเพื่อปรับขนาดภาพที่โหลด
-
ผูกฟังก์ชันกับการกำหนดค่าหน้าต่างหลัก
ตัวอย่าง
# Import the required libraries
from tkinter import *
from PIL import ImageTk, Image
# Create an instance of Tkinter Frame
win = Tk()
# Set the geometry of Tkinter Frame
win.geometry("700x450")
# Open the Image File
bg = ImageTk.PhotoImage(file="tutorialspoint.png")
# Create a Canvas
canvas = Canvas(win, width=700, height=3500)
canvas.pack(fill=BOTH, expand=True)
# Add Image inside the Canvas
canvas.create_image(0, 0, image=bg, anchor='nw')
# Function to resize the window
def resize_image(e):
global image, resized, image2
# open image to resize it
image = Image.open("tutorialspoint.png")
# resize the image with width and height of root
resized = image.resize((e.width, e.height), Image.ANTIALIAS)
image2 = ImageTk.PhotoImage(resized)
canvas.create_image(0, 0, image=image2, anchor='nw')
# Bind the function to configure the parent window
win.bind("<Configure>", resize_image)
win.mainloop()
ผลลัพธ์
การเรียกใช้โค้ดด้านบนจะแสดงหน้าต่างที่มีรูปภาพซึ่งสามารถปรับขนาดแบบไดนามิกได้
