Home » Tutorials » How to Take a Screenshot using Python

How to Take a Screenshot using Python

In today’s tutorial, we’re going to explore the process of capturing screenshots in Python, saving them with filenames that include a timestamp using the pyautogui and tkinter libraries. So, without further ado let’s dive in!

Table of Contents

Necessary Libraries

Make sure to install the tkinter and pyautogui libraries via your terminal or command prompt for the code to function properly.

$ pip install tk 
$ pip install pyautogui 

Importing Libraries

import tkinter as tk
from tkinter import filedialog
import pyautogui
from datetime import datetime

As you can see we start by importing tkinter, which creates a graphical user interface (GUI) rendering it easy to use for the user, then we import filedialog module, this module allows the user to choose the save location.

After that, we import pyautogui library, which we’ll use for taking screenshots, and lastly, datetime which helps in getting the current date and time.

Screenshot App Class

class ScreenshotApp:
   def __init__(self, root):
       self.root = root
       self.root.title("Screenshot App - The Pycodes") 

Next, we create a class called screenshotApp to make the code more organized, so first we start with the _init_ method which is like the setup phase for our screenshot app. It initializes the main window (root) and then makes a title for it.

Canvas and Widgets

 self.canvas = tk.Canvas(root, width=300, height=200)
       self.canvas.pack()

       self.create_widgets()

Following that, we create a canvas within the main window and then call the create_widgets method to create the GUI elements, in summary, what we did here is prepare the initial state and structure of the graphical user interface for the screenshot application.

Creating Widgets

   def create_widgets(self):
       self.screenshot_button = tk.Button(
           text="Take Screenshot", command=self.take_screenshot, bg="blue", fg="white"
       )
       self.canvas.create_window(150, 100, window=self.screenshot_button)

Here, we created a button labeled “Take Screenshot” with a blue background and white text, when this button is clicked it executes the take_screenshot command.

Taking a Screenshot

   def take_screenshot(self):
       try:
           # Hide the window to capture only the desktop
           self.root.iconify()


           # Capture screenshot
           screenshot = pyautogui.screenshot()


           # Show the window again
           self.root.deiconify()


           # Ask user for file path
           file_path = filedialog.asksaveasfilename(
               defaultextension=".png",
               filetypes=[("PNG files", "*.png"), ("All files", "*.*")],
           )


           # Save screenshot with a timestamp in the filename
           timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
           file_path_with_timestamp = f"{file_path}_{timestamp}.png"
           screenshot.save(file_path_with_timestamp)


           # Inform the user about the successful capture
           self.show_message("Screenshot captured successfully!")
       except Exception as e:
           # Inform the user if an error occurs
           self.show_message(f"Error: {e}")

The code presented here hides the window so that only the desktop is captured, then by using the pyautogui library the screenshot is taken, and once that’s done the window reappears so that the user can save the screenshot in a file path with a filename containing a timestamp while specifying the success or failure of the capture by message.

Displaying Messages

   def show_message(self, message):
       # Display a message to the user
       popup = tk.Toplevel(self.root)
       popup.title("Message")
       label = tk.Label(popup, text=message)
       label.pack(padx=10, pady=10)
       ok_button = tk.Button(popup, text="OK", command=popup.destroy)
       ok_button.pack(pady=10)

The above code displays a popup window with an “OK” button once clicked the popup window disappears.

Main Execution

if __name__ == "__main__":
   root = tk.Tk()
   app = ScreenshotApp(root)
   root.mainloop()

Finally, we create the main window and the ScreenshotApp is initialized starting the GUI loop event.

Example

Full Code

import tkinter as tk
from tkinter import filedialog
import pyautogui
from datetime import datetime


class ScreenshotApp:
   def __init__(self, root):
       self.root = root
       self.root.title("Screenshot App - The Pycodes")


       self.canvas = tk.Canvas(root, width=300, height=200)
       self.canvas.pack()


       self.create_widgets()


   def create_widgets(self):
       self.screenshot_button = tk.Button(
           text="Take Screenshot", command=self.take_screenshot, bg="blue", fg="white"
       )
       self.canvas.create_window(150, 100, window=self.screenshot_button)


   def take_screenshot(self):
       try:
           # Hide the window to capture only the desktop
           self.root.iconify()


           # Capture screenshot
           screenshot = pyautogui.screenshot()


           # Show the window again
           self.root.deiconify()


           # Ask user for file path
           file_path = filedialog.asksaveasfilename(
               defaultextension=".png",
               filetypes=[("PNG files", "*.png"), ("All files", "*.*")],
           )


           # Save screenshot with a timestamp in the filename
           timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
           file_path_with_timestamp = f"{file_path}_{timestamp}.png"
           screenshot.save(file_path_with_timestamp)


           # Inform the user about the successful capture
           self.show_message("Screenshot captured successfully!")
       except Exception as e:
           # Inform the user if an error occurs
           self.show_message(f"Error: {e}")


   def show_message(self, message):
       # Display a message to the user
       popup = tk.Toplevel(self.root)
       popup.title("Message")
       label = tk.Label(popup, text=message)
       label.pack(padx=10, pady=10)
       ok_button = tk.Button(popup, text="OK", command=popup.destroy)
       ok_button.pack(pady=10)


if __name__ == "__main__":
   root = tk.Tk()
   app = ScreenshotApp(root)
   root.mainloop()

Happy Coding!

Subscribe for Top Free Python Tutorials!

Receive the best directly.  Elevate Your Coding Journey!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
×