Welcome folks today in this blog post we will be building a screenshot capture
desktop app in python
using pillow
module. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the below libraries
using the pip
command as shown below
pip install pillow
Now we need to make an app.py
file and copy paste the following code
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import tkinter as tk from tkinter import filedialog from PIL import ImageGrab # Create a Tkinter root window root = tk.Tk() # Create a button to trigger the screenshot function screenshot_button = tk.Button(text="Take Screenshot", command=take_screenshot) screenshot_button.pack() # Run the Tkinter event loop root.mainloop() |
As you can see we are importing the tkinter
and pillow
module and then we have the button
to take the screenshot
of the window and save it as png
image.
Now we will be writing the function
which will execute when we hit the take screenshot
button to take the full screenshot and save it as png
image file
1 2 3 4 5 6 7 |
# Function to take a screenshot and save it to a file def take_screenshot(): # Ask the user to select a file to save the screenshot to file_path = filedialog.asksaveasfilename(defaultextension=".png") if file_path: # Use ImageGrab to capture the screen and save the image to the file ImageGrab.grab().save(file_path) |
As you can see in the above code we are using the filedialog
module and inside it we are asking the user
to save the screenshot
at a specified location and inside it we are providing the default
extension for the image which is .png
and then we are capturing
the screenshot using the pillow
module and we are using the grab()
method and then we are using the save()
method to save the image file at the specified
location.
FULL SOURCE CODE
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import tkinter as tk from tkinter import filedialog from PIL import ImageGrab # Create a Tkinter root window root = tk.Tk() # Function to take a screenshot and save it to a file def take_screenshot(): # Ask the user to select a file to save the screenshot to file_path = filedialog.asksaveasfilename(defaultextension=".png") if file_path: # Use ImageGrab to capture the screen and save the image to the file ImageGrab.grab().save(file_path) # Create a button to trigger the screenshot function screenshot_button = tk.Button(text="Take Screenshot", command=take_screenshot) screenshot_button.pack() # Run the Tkinter event loop root.mainloop() |