views:

142

answers:

2

I am trying to print the contents of a python tkinter canvas. I have tried using the postscript method of canvas to create a postscript file, but I get a blank page. I know this is because I have embedded widgets, and these do not get rendered by the postscript method.

Before I rewrite my program to create a more printer-friendly layout, can someone suggest a way to approach this problem? All of the programming books I have ever read approach the problem of sending output to a printer with a bit of hand-waving, something along the lines of: "It's a difficult problem that depends on interacting with the operating system." I also have a hard time finding resources about this because of all the pages related to printing to the screen.

I am using Python 2.6, on Ubuntu 9.04.

A: 

Well, it's a difficult problem that depends on interacting with the operating system. (Sorry, couldn't resist!)

The canvas-to-postscript solution only works for things drawn on the canvas -- it doesn't handle embedded windows. There are libraries that can convert a canvas to PDF, but I have no experience with them and don't know if they handle embedded windows or not (I'm guessing not).

There is pdflib, which is a commercial C library that can be integrated with python and tcl (and thus, Tkinter). I have no experience with the library, and I'm guessing it probably doesn't handle embedded windows either. I think it's more primitive -- giving you commands to create pages, headers, footers, etc.

This is definitely a problem with Tk; always has, likely always will since there doesn't seem to be much demand, or interest from anyone to solve the problem in a cross platform way.

Bryan Oakley
For this problem, I think I can redo the work by drawing directly on a canvas. I will either do that as a special function just for printing, or redo the screen functionality in the same way.For future reference, is there a gui package (ie wxpython) that is more adaptable to printing? Or do people often take this approach, of coding one version for the screen and coding separately for printing?
Eric
@Eric: I know that wxPython has some support for printing, but I've never used it so I don't know how robust it is. If printing is a deal-breaker you might want to try to install wxPython and run the demo to see if it does what you need.
Bryan Oakley
A: 

I think your butting up to the limits of Tkinter. If not for the widgets, another method is to draw the same image on a PIL image-draw object as the two have similar APIs.

A hacky workaround would be to programatically take a screen grab of the window area you want using ImageGrab in PIL.

wxPython is a decent alternative. Personally I prefer Qt, it certainly has excellent printer support. Also the Graphics View framework is outstanding.

Simon Hibbs