Search code examples
pythonpython-3.xscreenshotpython-3.4pyautogui

Screenshot several regions of the screen and save them with PyAutoGui - Python 3.4


I am a beginner in python programmation and I have a problem with screenshot function from PyAutoGui.

Here is my code:

#Libraries
import pyautogui, os

#Work Directory
os.chdir('C:/Users/mypath')

#Data and Variables:
ListOfNames=['T1.png','T2.png','T3.png']

#list of desired positions to screenshot:
Several_Regions=[(760, 142, 22, 23),(692, 352, 19, 21),(553, 456, 19, 21)]

#Program:  
for name in ListOfNames:
    for LeftTopWidthHeight in Several_Regions:
        pyautogui.screenshot('%s'%(name), region = LeftTopWidthHeight)

This is supposed to take a screenshot of each regions I mentionned in the list of regions Several_Regions in three .png files.

But it create 3 .png files with exactly the same region taken in screenshot that is the 3rd (and last) region (553, 456, 19, 21)...

Photo:

The 3 same files

Did I have forgot something somewhere? Please, help me to solve this problem :)


Solution

  • That is because in the nested for loops you actually make nine screenshots. And for every file, you save the third one: the last region. Because in the nested for loops you will actually make screenshots with parameters:

    • ListOfNames[0],Several_Regions[0],
    • ListOfNames[0],Several_Regions[1],
    • ListOfNames[0],Several_Regions[2],
    • ListOfNames[1],Several_Regions[0],
    • ListOfNames[1],Several_Regions[1],
    • ListOfNames[1],Several_Regions[2],
    • ListOfNames[2],Several_Regions[0],
    • ListOfNames[2],Several_Regions[1], and
    • ListOfNames[2],Several_Regions[2].

    So as you can see, for every ListOfNames, the last one with which you call that is Several_Regions[2].

    You can however use a zip to make sure the first region is saved to the first file name, etc.:

    for name,LeftTopWidthHeight in zip(ListOfNames,Several_Regions):
        pyautogui.screenshot('%s'%(name), region = LeftTopWidthHeight)

    Given however the names you show here are quite uniform, you can drop the ListOfNames and use enumerate(..) instead:

    for idx,LeftTopWidthHeight in enumerate(Several_Regions):
        pyautogui.screenshot('T%s.png'%idx, region = LeftTopWidthHeight)