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