User avatar
RogerW
Posts: 286
Joined: Sat Dec 20, 2014 12:15 pm
Location: London UK

A python prog to take picamera pictures

Thu May 14, 2015 2:05 pm

Give the interest in the piCamera and photo booths etc I thought it might be of interest to show this program which takes a 640x480 (you can change this) picture and displays it in a tkinter GUI program. Hopefully it might provide the basis for other programs.

Code: Select all

from sys import version_info
if version_info[0] < 3:
	import Tkinter as tk
else:
	import tkinter as tk

import picamera as pc

picture_width = 640
picture_height = 480

class Gif(tk.Canvas):
	# Widget to display an image
	def __init__(self,master,*args,**kwargs):
		tk.Canvas.__init__(self,master,*args,**kwargs)
	 
		# The canvas contains just the image
		self.gifid = self.create_image(0,0,anchor=tk.NW)
			
	def show(self,filename):
		# Called to display the image in filename
		self.img = tk.PhotoImage(file=filename)
		self.itemconfigure(self.gifid,image = self.img)         
		
class Mainframe(tk.Frame):
	def __init__(self,master,*args,**kwargs):
		tk.Frame.__init__(self,master,*args,**kwargs)
		
		# make sure camera is closed on exit
		self.bind('<Destroy>',self.on_destroy)
		
		# file that will be used to hold picture
		self.filename = 'PyCam.gif'
		       
		# creat the Gif widget that will show the picture
		self.gif = Gif(self,width=picture_width,height=picture_height)
		self.gif.grid(row = 0,column = 0)
		
		# A button to press to take the picture
		btn = tk.Button(self,text = 'Take picture',command = self.showpic)
		btn.grid(row = 1,column = 0)
		
		# create the camera object
		self.camera = pc.PiCamera()
		self.camera.resolution = (picture_width,picture_height)
		
	def showpic(self):
		# called when the button is pressed
		self.camera.capture(self.filename)
		self.gif.show(self.filename)
		
	def on_destroy(self,*args):
		# called whe the program ends
		self.camera.close()
		
class App(tk.Tk):
	def __init__(self):
		tk.Tk.__init__(self)
		
		self.title('PyCam')
		Mainframe(self).pack()
			   
App().mainloop()
Roger Woollett

Return to “Python”