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

boB Stepp robertvstepp at gmail.com
Wed Apr 15 19:00:43 CEST 2015


On Wed, Apr 15, 2015 at 10:39 AM, Peter Otten <__peter__ at web.de> wrote:
> boB Stepp wrote:
>
>> Solaris 10, Python 2.4.4

[...]

>
> I'm on linux and surprisingly
>
> subprocess.call(["import", "-window", window_title, postscript_file])
>
> worked. I admit it's a roundabout way...

I did not find the "import" command in my Unix reference, but found it
in the man pages on my Solaris workstation. It looks like this should
work without having to use the Canvas container, which was what I was
originally asking about.

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

Yes, it ran fine on Python 2.4.4.

> import Tkinter as tk

Question: I have been using "from Tkinter import *" as suggested in
"Programming Python" by Lutz. He remarks that unlike other situations,
this is generally safe with Tkinter. Is there a benefit to doing the
import as you have?

> 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])

At first I thought you had a typo here, but now I understand that "#
canvas.postscript(file="tmp.ps")" only gave you the window framework.
When I made my attempt to employ Zach's suggestion by embedding my
existing frames within a Canvas, I only got an empty white rectangle.
After searching online for that, I found references that Canvas'
postscript method only works for objects drawn on its canvas, NOT
embedded windows, frames, etc. This had me scratching my head again.
But then your post came in. I am very grateful for your solution!

> 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.


-- 
boB


More information about the Tutor mailing list