Python: Screenshot toggle switch (no Tkinter)

31 Views Asked by At

I am looking for a way to use a hot key 's' to capture repeated screenshots. When the script originally runs, I do not want any screenshots being captured, but when I press 's' I want screenshots being recorded at a designated time interval. When I press 's' again I want the screenshots to stop being recorded.

Here is my current script, I have been able to make this work when taking in a video and using Tkinter but in terms of screenshotting the screen based on a toggle switch, I have only gotten it to work when the script screenshots already.

import os
import numpy as np
import cv2
from mss import mss
from datetime import datetime
import time

def main():
    capturing = False
    
    # Create output directory
    output_dir = "output"
    os.makedirs(output_dir, exist_ok=True)
    capture_number = 0

    # Initialize screen capture
    with mss() as sct:
        monitor = sct.monitors[1]  # Adjust the monitor index as needed
        interval = 0.1  # Capture interval (10 times per second)

        try:
            print("Press 's' to start/stop capturing screenshots...")
            while True:
                start_time = time.time()
                frame = np.array(sct.grab(monitor))
                
                if capturing:
                    name = os.path.join(output_dir, f"capture{capture_number}.png")
                    cv2.imwrite(name, frame)
                
                # Check for key press to toggle capturing
                if cv2.waitKey(1) & 0xFF == ord('s'):
                    capturing = not capturing
                
                # Sleep to maintain capture rate
                sleep_time = interval - (time.time() - start_time)
                if sleep_time > 0:
                    time.sleep(sleep_time)
                capture_number +=1

        except KeyboardInterrupt:
            pass

if __name__ == '__main__':
    main()
0

There are 0 best solutions below