Main Problem
I wanted to get better pictures for the documentation of my Raspberry Pi project. It’s always better to have screenshots of demo than the pictures of the monitor running the program with a phone. When you google “how to capture screenshots on raspberry pi”, you get the simple answer - “Use a screenshot button on keyboard”. This does not work when you are running pygame or python animation program. While running, it does not let you use command or control on terminal.
Wait, what is Pygame?
Pygame is a Free and Open Source python programming language library for making multimedia applications like games. When you want to play animation on PiTFT, create simple user interface, or build games in Python, Pygame is a good library to use. You can learn more about the pygame here.
Another method tried, but failed
First method I tried was to decrease the screen size so that I could capture with the keyboard. However, as I mentioned earlier, the keyboard control is not working while pygame is running. Also, decreasing the pygame screen size only makes the area of control smaller and still uses the whole screen on monitor. Not the right way.
Just use pygame!
Here is the solution to this. We can use Pygame to capture and save the screenshots with pygame.image.save as shown on the stackoverflow page.
screen = pygame.display.set_mode(...)
pygame.image.save(screen, "screenshot.jpeg")
However, without condition, this will just capture once the program starts running. We want to capture the screen on a certain time like only when you press “screenshot button” on keyboard. We can use GPIO buttons! The code below uses GPIO 17 to save the pictures in the ./pi/images directory.
import RPi.GPIO as GPIO
import pygame
GPIO.setup(17, GPIO.IN, pull_up_down = GPIO.PUD_UP)
screenshot_num = 0
# take a screenshot - documentation purpose
if (not GPIO.input(17)):
pygame.image.save(screen, "./images/screenshot_"+str(screenshot_num)+".jpeg")
print(screenshot_num)
screenshot_num = screenshot_num + 1
When you click the GPIO 17 button, it will capture the whole screen of pygame and store with different names.
I hope this post helps!