206 THE OFFICIAL RASPBERRY PI BEGINNER'S GUIDE
There are a couple of clever tricks in these three lines of code. The first is in the capture
file name: using % 03 d tells Python to take a number and add as many zeroes to the front as it
needs to make it three digits long. Thus ‘1’ becomes ‘001’, ‘2’ becomes ‘002’, and ‘10’ becomes
‘010’. You need this in your program to keep your files in the correct order and to make sure
you’re not writing over a file you’ve already saved.
The % frame at the end of that line tells Python to use the number of the frame variable in
the file name. To make sure each file is unique, the last line – frame += 1 – increments the
frame variable by 1. The first time you press the button, frame will be increased from 1 to 2;
the next time, from 2 to 3; and so on.
At the moment, though, your code won’t exit cleanly when you’re finished taking pictures.
To make that happen, you need an except for your try. Type the following, remembering to
remove one level of indentation on the first line so Python knows it’s not part of the try section:
except KeyboardInterrupt:
camera.stop_preview()
break
Your finished program will look like this:
from picamera import PiCamera
from time import sleep
from gpiozero import Button
camera = PiCamera()
button = Button( 2 )
camera.start_preview()
frame = 1
while True:
try:
button.wait_for_press()
camera.capture('/home/pi/Desktop/animation/frame%03d.jpg'
% frame)
frame += 1
except KeyboardInterrupt:
camera.stop_preview()
break
Try clicking Run, but instead of pressing the button, press the CTRL and C keys on the
keyboard. You don’t need to press both keys at the same time: just hold down CTRL, press
and release C, then release CTRL. These two keys act as an interrupt, telling Python to
stop what it’s doing. Without the except KeyboardInterrupt: line, Python would
immediately quit and leave the camera preview blocking your screen; with that line in place,