แพ็กเกจ PIL หรือ Pillow ใน Python ให้วิธีการประมวลผลรูปภาพในโปรแกรม เราสามารถเปิดรูปภาพ จัดการรูปภาพสำหรับการใช้งานต่างๆ และใช้แสดงข้อมูลได้เช่นกัน เพื่อแสดงรูปภาพในแอปพลิเคชัน เรามักอ้างอิงถึงวิดเจ็ต Canvas เนื่องจาก Canvas มีฟังก์ชันมากมายสำหรับเพิ่มรูปภาพและวัตถุ เราจึงสามารถใช้มันแสดงรูปภาพได้
เพื่อเปลี่ยนรูปภาพเฉพาะ เราสามารถกำหนดค่า Canvas โดยใช้คอนสตรัคเตอร์ itemconfig() ซึ่งรับไฟล์รูปภาพที่ต้องการอัปเดตและแสดงบนหน้าต่าง
ตัวอย่าง
สำหรับตัวอย่างนี้ ให้ใช้รูปภาพ 3 ไฟล์ตามต้องการ และบันทึกไว้ในไดเรกทอรีโปรเจกต์เดียวกัน
# Import the required library
from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
# Create an instance of tkinter frame
win = Tk()
# Set the geometry
win.geometry("750x400")
# Define function to update the image
def update_image():
canvas.itemconfig(image_container, image=img2)
# Create a canvas and add the image into it
canvas = Canvas(win, width=650, height=350)
canvas.pack()
# Create a button to update the canvas image
button = ttk.Button(win, text="Update", command=lambda: update_image())
button.pack()
# Open an Image in a Variable
img1 = PhotoImage(file="logo.png")
img2 = PhotoImage(file="logo2.png")
img3 = PhotoImage(file="logo3.png")
# Add image to the canvas
image_container = canvas.create_image(0, 0, anchor="nw", image=img1)
win.mainloop()
ผลลัพธ์
การรันโค้ดด้านบนจะแสดงหน้าต่างพร้อม Canvas และปุ่มสำหรับอัปเดตรูปภาพบน Canvas

ตอนนี้ คลิกปุ่ม "Update" เพื่อเปลี่ยนรูปภาพ
