I am trying to print the contents of a python tkinter canvas. I have tried using the postsc开发者_StackOverflow中文版ript 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.
Turns out that you have to update the canvas before exporting the postscript. Like so:
from Tkinter import *
root = Tk()
canvas = Canvas(bg='white', width = 200, height = 200)
canvas.pack()
canvas.create_line(0, 0, 199, 199, fill="blue", width = 5)
canvas.create_line(0, 199, 199, 0, fill="blue", width = 5)
canvas.update()
canvas.postscript(file = "x.ps")
root.mainloop()
Thanks to Rio here for the solution.
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.
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.
精彩评论