0
votes

I'm trying to draw a grid with tkinter canvas. The logic is fairly simple: for each node in the grid, I draw a rectangle using its top-left and bottom-right corners [code below].

The problem is that tkinter doesn't render the left and top borders of nodes in the first column and row respectively. It's like tkinter is offsetting the canvas by some small # of pixels. Is there a config to correct this? My current workaround is to subtract some small value from cellW and cellH, then offset every node's x1 and y1...this is very hacky. missing left and top borders

I am not doing anything weird, just a simple canvas on a root window.

import tkinter as tk

winH = 400
winW = 400
ncols = 10
nrows = 10
cellW = winW / ncols
cellH = winH / nrows

class Node:
    def __init__(self, row, col):
        self.row = row
        self.col = col
        return

def generatGrid(nrows, ncols):
    grid = []
    for r in range(nrows):
        row = [ Node(r, c) for c in range(ncols) ]
        grid.append(row)
    return grid

def drawNode(canvas, node):
    x1 = cellW * node.col
    y1 = cellH * node.row
    x2 = x1 + cellW
    y2 = y1 + cellH
    canvas.create_rectangle(x1, y1, x2, y2)
    return

def drawGrid(canvas, grid):
    for row in grid:
        for node in row:
            drawNode(canvas, node)
    return

window = tk.Tk()
canvas = tk.Canvas(window, width=winW, height=winH)
canvas.pack()

grid = generatGrid(nrows, ncols)
drawGrid(canvas, grid)

window.mainloop()
1
Please provide a minimal reproducible example - your code is missing some important parts which prevent us from running your code.Bryan Oakley
@BryanOakley, I've updated the code. Thanks.eyeezzi

1 Answers

1
votes

One of the things I find annoying about the canvas is that the border is part of the coordinate space. When you draw a line on the left edge, it gets obscured by the border.

Is there a config to correct this?

Yes.

You can get around this by completely turning off the attributes related to the border:

canvas = tk.Canvas(window, width=winW, height=winH, 
                   borderwidth=0, highlightthickness=0)

If you want to have some sort of border around the canvas, you can place the canvas in a frame, and use the frame to draw the border.