[Tutor] How to get a Tkinter window to print a color copy of itself as a .pdf file?

Peter Otten __peter__ at web.de
Wed Apr 15 17:39:53 CEST 2015


boB Stepp wrote:

> Solaris 10, Python 2.4.4
> 
> I have very little experience with issuing print commands using a Unix
> environment. Despite this, I wish to design a Tkinter window with a
> "Print" button, which, when clicked, would create a copy of the
> contents of the window as a .pdf file. GhostScript is available on my
> systems.
> 
> I know that the Canvas container has the ability to print itself to a
> postscript file, but I do not want to use Canvas as my container
> object. So I am hopeful this is as simple as discovering the proper
> command to associate with a button, which will generate a color
> postscript file of the containing window. Once I can get that file, I
> know how to get a .pdf out of it.
> 
> The main software that we use on these systems has this print command
> associated with its color printer *button*:
> 
> lp -c -d ricoh -o resolution=1200 -o profile=photo -o dithering=photo
> -o colorsettings=superfine -o black=k -o papper=letter -o itray=tray1
> 
> BTW, "papper" is what is actually in this software product's color
> printer settings. But can this be correct? Anyway, it does print to
> *paper*!
> 
> I suspect that some variant of this command associated with a print
> button would print *something*, but how do I get it to print the
> specific window containing the to-be-designed print button? Also, I
> need it to print a postscript file, not print to paper. I suspect this
> is another configuration setting that I need to research.
> 
> As always, many thanks in advance!

I'm on linux and surprisingly

subprocess.call(["import", "-window", window_title, postscript_file])

worked. I admit it's a roundabout way...

Here's the complete experiment; I ran it with Python 2.7, but that shouldn't 
make a difference.

import Tkinter as tk
import subprocess

window_title = "gewizzede"
postscript_file = "tmp_snapshot.ps"

def print_canvas():
#    canvas.postscript(file="tmp.ps")
    subprocess.call(["import", "-window", window_title, postscript_file])

root = tk.Tk()
root.title(window_title)

canvas = tk.Canvas(root, width=200, height=200)
canvas.pack()

button = tk.Button(root, text="Print", command=print_canvas)
button.pack()

demo = tk.Button(root, text = "demo widget button")
canvas.create_window(50, 50, window=demo)
canvas.create_rectangle(25, 25, 75, 150, fill="red")
root.mainloop()

You might guess from the above that I tried Zachary's suggestion first, but 
that printed only the red rectangle, not the demo button.



More information about the Tutor mailing list