Search code examples
pythontkintercanvas

Tkinter Canvas postscript saves as 1x1


I am making trying to make a chess game using Canvas. But when i try to get the image that i made using canvas, it returns a 1x1 image.

Heres the code that i am using

from tkinter import *
from PIL import Image, ImageTk, EpsImagePlugin
import io

EpsImagePlugin.gs_windows_binary = r'gs\bin\gswin64c.exe'

def interpret(c, p, x, y):
    path = "images/" + c + '/' + c[0] + p + ".png"

    win = Tk()
    win.geometry("1200x1200")
    canvas= Canvas(win, width= 1200, height=1200)
    canvas.pack()
    table = ImageTk.PhotoImage(Image.open("images/table.png"))
    canvas.create_image(0,0,anchor=NW,image=table)
    wp = ImageTk.PhotoImage(Image.open(path))
    canvas.create_image((150 * x) - 150, (150 * y) - 150,anchor=NW,image=wp)

    postscript = canvas.postscript(colormode='color')
    
    img = Image.open(io.BytesIO(postscript.encode('utf-8')))
    img.show()      
    
interpret('black', 'p', 4, 5)

I tried saving it as an eps and converting it to a PNG, but still doesnt work. I expected that it saved as a 1200x1200 (table.png resolution) PNG file


Solution

  • The problem is likely that the canvas hasn't had a chance to render yet so tkinter doesn't know the size of the widget, defaulting to its current 1x1 size.

    From the official tcl/tk documentation on the postscript method:

    If the canvas is freshly created it may still have its initial size of 1x1 pixel so nothing will appear in the Postscript. To get around this problem either invoke the update command to wait for the canvas window to reach its final size, or else use the -width and -height options to specify the area of the canvas to print.