The only built-in image save function for Tkinter canvas is a postscript save. This didn’t work for me and instead of finding out why, I thought of another way which works great.
Create a frameless canvas window using ‘overrideredirect(1)’, place the canvas in the top corner and use PIL’s ImageGrab and save the images. Finally, ‘destroy’ the window when finished, since there is no kill button in the top corner. Here is an example that animates a polygon moving on the canvas.
from Tkinter import *
from PIL import ImageGrab
from numpy import array
import os
class App(Tk):
def __init__(self, parent):
Tk.__init__(self, parent)
self.overrideredirect(1)
self.width = 900
self.height = 640
self.initialize()
def initialize(self):
self.c = Canvas(self, width=self.width, height=self.height, background='white')
self.c.pack(side=RIGHT, expand=YES, fill=BOTH)
self.update()
self.run_anim()
self.destroy()
def run_anim(self):
print os.getcwd()
c = self.c
polyo = array([34,60,226,15,419,60,359,151,91,151])
polyd = array([205,253,296,187,388,253,353,360,239,360])
trantime = 20
for i in xrange(trantime):
c.delete('pol')
ptrans = (float(i)/trantime)*polyd+(trantime-float(i))/trantime*polyo
c.create_polygon(list(ptrans), width=4, outline='black', fill='red', tags='pol')
self.update()
savename = 'im_{0:0>6}'.format(i)
ImageGrab.grab((0,0,900,640)).save(savename + '.jpg')
app = App(None)
app.mainloop()