## 用按键控制相机 用开关触发树莓派摄像头```PiCamera```拍摄一张照片,或者当开关按下的时候,树莓派摄像头就会拍一张照片。`button.when_pressed=camera.capture`这种写法不能够实现预期目标,因为摄像头的`capture()`方法需要一个`output`参数,表示拍摄照片保存的路径和文件名。不过,我们可以用一个自定义的无参函数实现按键拍照。 ~~~ from gpiozero import Button from picamera import PiCamera from datetime import datetime from signal import pause button = Button(2) camera = PiCamera() def capture(): timestamp = datetime.now().isoformat() camera.capture('/home/pi/%s.jpg' % timestamp) button.when_pressed = capture pause() ~~~ 按下开关,调用自定义的无参函数`capture`,在函数内部拍照,并把照片保存为`拍照时间.jpg`。 另外一个例子是用一个按钮来开启或者停止摄像头预览,另外一个按钮用来拍照: ~~~ from gpiozero import Button from picamera import PiCamera from datetime import datetime from signal import pause left_button = Button(2) right_button = Button(3) camera = PiCamera() def capture(): timestamp = datetime.now().isoformat() camera.capture('/home/pi/%s.jpg' % timestamp) left_button.when_pressed = camera.start_preview left_button.when_released = camera.stop_preview right_button.when_pressed = capture pause() ~~~