Python มีไลบรารีโมดูลและฟังก์ชันอุดมสมบูรณ์ที่ช่วยสร้างและพัฒนาแอปพลิเคชัน Tkinter เป็นไลบรารี Python ที่รู้จักกันดีสำหรับสร้างแอปพลิเคชัน GUI หากต้องการพัฒนาแอปพลิเคชันที่ถ่ายภาพหน้าจอหน้าต่าง เราสามารถใช้ Tkinter สร้าง GUI ของแอปพลิเคชัน ขั้นตอนต่อไปนี้จะช่วยเข้าใจการทำงานของแอปพลิเคชัน:
- Required Libraries – Pillow (PIL) สำหรับประมวลผลภาพ, Time Module ใน Python สำหรับสุ่มชื่อไฟล์และประมวลผล epochs
- สร้าง Label widget ในหน้าต่างและเพิ่มปุ่มถ่ายภาพหน้าจอ
- กำหนดฟังก์ชัน screenshot() ที่จะถ่ายภาพหน้าจอและบันทึกไฟล์ในไดเรกทอรีท้องถิ่น
- เพื่อให้หน้าต่าง Tkinter ไม่ถูกถ่ายรวมในภาพ ใช้ฟังก์ชัน withdraw() ถอนหน้าต่าง
ตัวอย่าง
# Import the required libraries
from tkinter import *
import time
from PIL import ImageTk, Image
import pyautogui as pg
# Create an instance of tkinter frame or window
win = Tk()
# Set the size of the window
win.geometry("700x350")
# Define a function for taking screenshot
def screenshot():
random = int(time.time())
filename = "C:/Users/Sairam/Documents/" + str(random) + ".jpg"
ss = pg.screenshot(filename)
ss.show()
win.deiconify()
def hide_window():
# hiding the tkinter window while taking the screenshot
win.withdraw()
win.after(1000, screenshot)
# Add a Label widget
Label(win, text="Click the Button to Take the Screenshot", font=('Times New Roman', 18, 'bold')).pack(pady=10)
# Create a Button to take the screenshots
button = Button(win, text="Take Screenshot", font=('Aerial 11 bold'), background="#aa7bb1", foreground="white", command=hide_window)
button.pack(pady=20)
win.mainloop()ผลลัพธ์
การรันโค้ดจะแสดงหน้าต่างที่มีปุ่มและ Label text

เมื่อคลิกปุ่ม จะถ่ายภาพหน้าจอและบันทึกในไดเรกทอรีท้องถิ่น
