Python Tutorials

How to get a Screenshot with Python

PIL image manipulation library of Python has more tricks under its sleeve than editing images such as taking a screenshot of your screen.

Used Where?

  • To capture screen
  • Face Recognition
  • Interacting with games and software
  • Research
  • Security
  • Surveillance

Let’s import ImageGrab from the PIL the library:

from PIL import ImageGrab

Estimated Time

3 mins

Skill Level

Intermediate

Modules

ImageGrab

Libraries

PIL

Tutorial Provided by

HolyPython.com

ImageGrab in action

All it takes is a 2 line implementation in Python:

im=ImageGrab.grab()
im.save("Screenshot.jpg")

You might want to save this little code as “my_program.py” and schedule it with Windows so it takes screenshots of the computer at predefined intervals such as every hour or minute.

In that case, you will need the filename of the screenshot to be different each time.

One way to tackle this is using the exact time of the screenshot in the filename.
This can easily be done with time library:

import time
savetime=time.strftime("%Y-%b-%d__%H_%M_%S",time.localtime())

Here is the full code:

from PIL import ImageGrab
import time

im=ImageGrab.grab()

moment=time.strftime("%Y-%b-%d__%H_%M_%S",time.localtime())
im.save(savetime+"Screenshot.jpg")

Screenshot will be saved either in the default Python working directory or if you saved your script in a file, in the same directory where that .py file is.

Conclusion

Additionally ImageGrab can be used to obtain continuous screen feed with the help of a loop structure. You can check out this tutorial to see a sample implementation.

Pixel positions
Usag1r

Share
Published by
Usag1r

Recent Posts

Benefits of Bokeh over Python visualization libraries like Seaborn, Matplotlib & Plotly

ContentsIntroductionBokeh vs Seaborn & MatplotlibBokeh vs PlotlySummary Introduction As computer science activity booms, you might…

12 months ago

History of Speech-to-Text AI models

History of Speech-to-Text Models​ & Current Infrastructure As speech technology continues to advance, so too…

1 year ago

Advanced Level Python Tips & Tricks

Python Tips & Tricks (Part III) Advanced Level HolyPython.com Here are more Python tips about…

1 year ago

Intermediate Level Python Tips & Tricks

Python Tips & Tricks (Part II) Intermediate Level HolyPython.com The list continues with slightly more…

1 year ago

When is Python 4 Coming Out?

Almost 15 years after the release of Python 3 many people are wondering when Python…

2 years ago

How to Create an app with a 3D model using VIKTOR

Introduction We are going to need smart engineering solutions to solve our planet's problems (and…

2 years ago