Tkinter เป็นไลบรารี Python มาตรฐานสร้างแอปพลิเคชัน GUI แสดงภาพใช้ไลบรารี PIL หรือ Pillow
สมมติต้องการสร้างแอปถ่ายสกรีนชอตหน้าต่างและแสดงภาพที่จับได้ในอีกหน้าต่าง สามารถทำตามขั้นตอน:
- นำเข้าไลบรารีที่จำเป็น
- สร้างปุ่มสำหรับถ่ายสกรีนชอต
- กำหนดฟังก์ชันถ่ายสกรีนชอต
- ในฟังก์ชัน กำหนด coords และ region สำหรับถ่ายสกรีนชอต
- สร้างหน้าต่าง Toplevel และกำหนด label image
- Pack widget และแสดงภาพเอาต์พุต
ตัวอย่าง
# Import the required libraries
from tkinter import *
import pyautogui
from PIL import ImageTk, Image
# Create an instance of tknter frame or window
win = Tk()
# Set the size of the window
win.geometry("700x350")
# Define a function to take the screenshot
def take_screenshot():
x = 500
y = 500
# Take the screenshot in the given corrds
im1 = pyautogui.screenshot(region=(x, y, 700, 300))
# Create a toplevel window
top = Toplevel(win)
im1 = ImageTk.PhotoImage(im1)
# Add the image in the label widget
image1 = Label(top, image=im1)
image1.image = im1
image1.place(x=0, y=0)
Button(win, text='Take ScreenShot', command=take_screenshot).pack(padx=10, pady=10)
win.mainloop()
ผลลัพธ์
รันโค้ด จะแสดงหน้าต่างพร้อมปุ่มถ่ายสกรีนชอต

คลิกปุ่ม "Take ScreenShot" จะจับภาพหน้าจอขนาด 700x300 พิกเซล เริ่มจากพิกัด (500, 500)
