如何使用Python(Tkinter)擷取視窗截圖?


Python擁有豐富的模組和函式庫,允許我們構建和開發功能強大的應用程式。Tkinter是一個著名的Python庫,用於建立基於GUI的應用程式。如果我們想開發一個擷取視窗截圖的應用程式,我們肯定可以使用Tkinter來構建應用程式的GUI。以下應用程式的步驟將有助於瞭解我們的應用程式是如何工作的:

  • **所需庫** – Pillow(PIL)用於影像處理,Python中的Time模組用於隨機化檔名和週期處理。

  • 在視窗中建立一個標籤小部件,並新增一個按鈕來擷取螢幕截圖。

  • 定義一個函式,**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()

輸出

執行以上程式碼將顯示一個包含按鈕和標籤文字的視窗。

當我們單擊按鈕時,它將擷取視窗的螢幕截圖並將其儲存在本地目錄中。

更新於:2021年6月18日

2K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告