How to take a screenshot of the window using Python?(Tkinter)

TkinterPythonGUI-Programming

Python has a rich library of modules and functions that allows us to build and develop featured applications. Tkinter is a well-known Python library that is used for creating GUIbased applications. If we want to develop an application that takes a screenshot of the window, then we can definitely use Tkinter to build the GUI of the application. The following stages of the application will help to know how our application works,

  • Required Libraries – Pillow (PIL) for Image Processing, Time Module in Python for Randomizing the Filename and epochs processing.

  • Create a Label widget in the window and add a Button to take the screenshot.

  • Define a function, screenshot(), that will take the screenshot of the window and save the file in a local directory.

  • In order to keep the Tkinter window away from taking screenshots as well as in the image, we can use withdraw() function to withdraw the image.

Example

# 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()

Output

Running the above code will display a window that contains a button and a Label text.

When we click the button, it will take a screenshot of the window and save it in a local directory.

raja
Published on 18-Jun-2021 13:22:45
Advertisements