1

I'm trying to 'export' a tkinter canvas to a png file, as in this answer: https://stackoverflow.com/a/55385764/15862653

I created a sample canvas and a button that triggers a function to export it to png:

import tkinter as tk
from PIL import Image

def save_as_png(canvas, fileName):
    canvas.postscript(file='./' + fileName + '.eps', colormode='color')
    img = Image.open(fileName + '.eps')
    img.convert()
    img.save(fileName + '.png', 'png')


root = tk.Tk()
canvas = tk.Canvas(root, width=100, height=100)
text = canvas.create_text(50, 50, anchor='center', text='Some text')
button = tk.Button(root, text='Save canvas', command=lambda: save_as_png(canvas, 'my canvas'))
canvas.pack()
button.pack()

root.mainloop()

The image that results has extremely low resolution, though. I took me a while even to understand that 'Some text' is actually what is written:

enter image description here

I tried fiddling with the arguments (dpi, quality, compression_level) of both the open and the save methods, with no luck.

1 Answers1

1

According to the tkdoc on pagewidth or pageheight of .postscript():

Specifies that the Postscript should be scaled in both x and y so that the printed area is size high on the Postscript page. Size consists of a floating-point number followed by c for centimeters, i for inches, m for millimeters, or p or nothing for printer's points (1/72 inch). Defaults to the height of the printed area on the screen. If both -pageheight and -pagewidth are specified then the scale factor from -pagewidth is used (non-uniform scaling is not implemented).

# set the output width to 1000 pixels
canvas.postscript(file='./'+fileName+'.eps', colormode='color', pagewidth=1000)
acw1668
  • 40,144
  • 5
  • 22
  • 34
  • Thanks! If they defaults to the printed area on the screen, why don't I get the same resolution I see on the canvas without setting those arguments? – Felipe Martins Apr 29 '22 at 15:42