Tkinter เป็นไลบรารี Python มาตรฐานที่ใช้ในการสร้างและพัฒนาแอปพลิเคชันที่ใช้ GUI ในการแสดงรูปภาพ เราใช้ไลบรารี PIL หรือ Pillow
สมมติว่าเราต้องการสร้างแอปพลิเคชันที่จะถ่ายภาพหน้าจอของหน้าต่างและแสดงภาพที่ถ่ายในหน้าต่างอื่น เพื่อให้บรรลุสิ่งนี้ เราสามารถทำตามขั้นตอนด้านล่าง -
-
นำเข้าไลบรารีที่จำเป็น
-
สร้างปุ่มสากลเพื่อจับภาพหน้าจอ
-
กำหนดฟังก์ชันเพื่อจับภาพหน้าจอ
-
ในฟังก์ชันที่กำหนด ให้กำหนด coords และภูมิภาค ซึ่งเราต้องการจับภาพหน้าจอ
-
สร้างหน้าต่างระดับบนสุดและกำหนดภาพป้ายกำกับในนั้น
-
แพ็ควิดเจ็ตและแสดงภาพที่ส่งออก
ตัวอย่าง
# 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() ผลลัพธ์
เมื่อเรารันโค้ด จะแสดงหน้าต่างพร้อมปุ่มสำหรับจับภาพหน้าจอ

ตอนนี้ คลิกปุ่ม "ถ่ายภาพหน้าจอ" และจับภาพหน้าจอขนาดกว้าง 700px และสูง 300 px โดยเริ่มจากพิกัด (x=500, y=500)
