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

วิธีใช้ PIL ร่วมกับ Tkinter

แพ็กเกจ PIL หรือ Pillow ใน Python ให้วิธีการประมวลผลรูปภาพในโปรแกรม เราสามารถเปิดรูปภาพ จัดการรูปภาพสำหรับการใช้งานต่างๆ และใช้แสดงข้อมูลได้เช่นกัน เพื่อใช้แพ็กเกจ PIL ใน Tkinter คุณต้องติดตั้งไลบรารี Python Pillow ในสภาพแวดล้อมของคุณ

ในการติดตั้ง Pillow ให้พิมพ์คำสั่ง pip install pillow เมื่อติดตั้งสำเร็จแล้ว คุณสามารถนำเข้าโมดูลในโปรเจกต์และนำไปใช้งานต่อได้

ตัวอย่าง

ในตัวอย่างนี้ เราแสดงรูปภาพในวิดเจ็ต Canvas โดยใช้แพ็กเกจ Python Pillow

# 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("700x350")

# Create a canvas widget
canvas = Canvas(win, width=700, height=350)
canvas.pack()

# Load the image
img = ImageTk.PhotoImage(file="opera.jpg")

# Add the image in the canvas
canvas.create_image(350, 200, image=img, anchor="center")

win.mainloop()

ผลลัพธ์

ถ้าเรารันโค้ดด้านบน จะแสดงรูปภาพในหน้าต่าง

วิธีใช้ PIL ร่วมกับ Tkinter