Python รองรับแพ็กเกจ PIL หรือ Pillow ซึ่งเป็นไลบรารีโอเพนซอร์สสำหรับเปิด จัดการ และบันทึกรูปภาพหลายรูปแบบในโปรเจกต์ Python เราสามารถใช้ในแอปพลิเคชัน Tkinter เพื่อประมวลผลและแสดงภาพ
Widget Label ใน Tkinter ใช้แสดงข้อความและภาพ เพื่อแสดงภาพด้วย Label widget ในแอปพลิเคชัน Tkinter ให้ทำตามขั้นตอน:
- ตรวจสอบว่าแพ็กเกจ Pillow หรือ PIL ติดตั้งในระบบแล้ว
- โหลดภาพลงในตัวแปรด้วยฟังก์ชัน ImageTk.PhotoImage(file=file_location)
- สร้าง Label widget กำหนดค่า image เป็นภาพที่โหลด
- รันโค้ดเพื่อแสดงภาพ
ตัวอย่าง
# 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 window
win.geometry("700x470")
# load the image and convert it into Tkinter Photoimage
bg=ImageTk.PhotoImage(file="baseball.png")
# Add a label widget to display the image
label=Label(win, image=bg)
label.place(x=0, y=0)
win.mainloop()ผลลัพธ์
รันโค้ดเพื่อแสดงภาพในหน้าต่าง Tkinter
