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
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 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
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.
If for some reason you happen to use wxPython there is a recipe for you as well.
$ 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
This program needs access to the screen. Please run with a
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
y indexing within
im is swapped here, so double-check your code.
Second method use Qt
from PyQt5.QtCore import QRect, QPoint, QSize
You can also omit using
QSize structures and pass numbers as arguments directly
x = 0
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.