[Tkinter-discuss] Convert Canvas to bitmap image

Michael Lange klappnase at web.de
Mon Oct 23 12:53:24 EDT 2017


On Mon, 23 Oct 2017 12:07:20 +0000
Vasilis Vlachoudis <Vasilis.Vlachoudis at cern.ch> wrote:

> Dear all,
> what can be the most efficiency way of converting the canvas to a
> bitmap (what ever type, gif png, jpg...) image? Right now we are saving
> to postscript and then using the PIL library convert it to bitmap.

you can use the tkImg library to do that. tkImg's "window" image type
allows you to create "screenshots" of Tk widgets on the fly.
To load the "window" image type, do:

    somewidget.tk.call('package', 'require', 'img::window')

Or to load all available image formats:

    somewidget.tk.call('package', 'require', 'Img')

Then you should be able to load the canvas as image and export the
image to a gif or png file (or any other format your tkImg install
supports) with something like:

    img = Tkinter.PhotoImage(format='window', data=canvas._w)
    img.write('canvas.png', format='png')
    del img

tkImg can be a bit tricky though. I have had problem with the window
image type when using Tkinter's default widget names. From my experience
it seems a good idea to create the widget in question and all its
ancestors with the widget name explicitely set, as in

   f0 = Frame(parent, name='f0')

Loading all image types at once also often causes problems (resp.
crashes), so I recommend to explicitely only load the image types you
really need.

Best regards


.-.. .. ...- .   .-.. --- -. --.   .- -. -..   .--. .-. --- ... .--. . .-.

When a child is taught ... its programmed with simple instructions --
and at some point, if its mind develops properly, it exceeds the sum of
what it was taught, thinks independently.
		-- Dr. Richard Daystrom, "The Ultimate Computer",
		   stardate 4731.3.

More information about the Tkinter-discuss mailing list