Search code examples
pythonmultithreadingscreenshotpyautogui

Python save multiple images with pyautogui


Im making a screenshot program that takes a screenshot every 5 seconds. But it will only save 1 .png file. Its becuase the name is the same every time and it wont make duplicates.

How do i save them as image(1), image(2), image(3)....

This is my code:

import pyautogui
import threading

#myScreenshot = pyautogui.screenshot()
#myScreenshot.save(r'C:\Users\censored\Desktop\screenshot\imgs\image.png')


def ScreenShotTimer():
    threading.Timer(5.0, ScreenShotTimer).start()
    myScreenshot = pyautogui.screenshot()
    myScreenshot.save(r'C:\Users\censored\Desktop\screenshot\imgs\image.png')
    print('Program Is Still Running.')

ScreenShotTimer()

Thanks for helping me!


Solution

  • import pyautogui
    
    # Solution 1
    
    import time
    
    for i in range(60):
        ss = pyautogui.screenshot()
    
        ss.save(f"SS {i}.png")
    
        time.sleep(5)
    
    
    # Solution 2
    
    import threading
    import functools as ft
    
    def screenshot(index: int = 0):
        ss = pyautogui.screenshot()
    
        ss.save(f"SS {index}.png")
    
        threading.Timer(5.0, ft.partial(screenshot, index+1)).start()
    
    screenshot()
    

    Two solutions.

    1. Uses a for loop (could easily be a while loop).
    2. Uses threading.Timer and functools.partial to call the function again, with a different parameter.