Creating desktop screenshots with Python
In this article I’m going to show how to accomplish a simple task of creating a screenshot using various Python tools. Alongside we’ll see other useful methods of working with pictures. Let’s start with the simplest way possible.
We’ll be using pyscreenshot package pip install pyscreenshot
1 | import pyscreenshot |
Three lines of code (importing/instantiating/saving). Is there anything easier than that? Actually, pyscreenshot is a wrapper around various backends, so to make it work you have to have at least one of it installed. pip install Pillow
will work for this example by using popular Python fork for PIL called Pillow.
PyAutoGui
PyAutoGUI is really powerful module for automation. It’s capable of moving your mouse, control keyboard and handle user inputs. It also has a handy way of creating a screenshot but basically it’s again a wrapper around Pillow. So go with pip install pyautogui
and add another three simple lines of code
1 | import pyautogui |
PyQt
PyQt is even more powerful toolkit allowing you to create complex GUI applications. It’s a set of binding for Qt framework which Python users can utilize. The program will be a little longer because you need to instantiate your application object but really you might want to use this snippet only if you already have some code written PyQt or plan to develop graphical application. As usually we start by installing package with pip install pyqt5
. There is an older version PyQt4, so make sure you didn’t accidentally install that because they are not totally compatible and you should be using newer release.
1 | import sys |
wxPython?
If for some reason you happen to use wxPython there is a recipe for you as well.
1 | import wx |
The only important note is that you should install/build your Python distribution with framework support enabled. With pyenv it’s simple as the following
1 | $ export PYTHON_CONFIGURE_OPTS="--enable-framework" |
Otherwise you might get annoying error which prevents you from running the code, error message example from my laptop below
1 | This program needs access to the screen. Please run with a |
Cropping a screenshot
Usually you are interested in some specific region of the image (called ROI/box) not the fullscreen. Here’s couple of method how that can be done. First one does the job with OpenCV pip install opencv-contrib-python
1 | import cv2 |
Note that x
and y
indexing within im
is swapped here, so double-check your code.
Second method use Qt
1 | from PyQt5.QtCore import QRect, QPoint, QSize |
You can also omit using QPoint
and QSize
structures and pass numbers as arguments directly
1 | x = 0 |
or even cropped = im.copy(x, y, width, height)
.
I hope with such variety of methods everybody will be able to find approach to fit their toolset. Happy coding and see you soon.