我正在尝试使用Tkinter将网格绘制成具有多个行和列的矩形。我几乎拥有它,但是,我不知道为什么,画布上没有显示两条边界线。
import tkinter as tk
class GridWindow:
def __init__(self, parent):
self.myParent = parent
self.myContainer1 = tk.Frame(parent)
self.myContainer1.pack()
self.cellwidth = 25
self.cellheight = 25
self.rect = {}
def draw_grid(self, rows, columns):
self.myCanvas = tk.Canvas(self.myContainer1)
self.myCanvas.configure(width=self.cellheight*rows,
height=self.cellwidth*columns)
self.myCanvas.pack(side=tk.RIGHT)
for column in range(rows):
for row in range(columns):
x1 = column * self.cellwidth
y1 = row * self.cellheight
x2 = x1 + self.cellwidth
y2 = y1 + self.cellheight
self.rect[row, column] = self.myCanvas.create_rectangle(x1, y1, x2, y2, fill="white")
def runApp(rows, columns):
root = tk.Tk()
myapp = GridWindow(root)
myapp.draw_grid(rows, columns)
root.mainloop()
if __name__ == '__main__':
runApp(10, 10)
使用该代码,窗口如下所示:
我设法用一点点黑客来解决这个问题,但我不知道为什么会这样。唯一不同的是,现在我为每个画布尺寸添加2个像素,每个单元尺寸增加4个像素。代码如下:
import tkinter as tk
class GridWindow:
def __init__(self, parent):
self.myParent = parent
self.myContainer1 = tk.Frame(parent)
self.myContainer1.pack()
self.cellwidth = 25
self.cellheight = 25
self.rect = {}
def draw_grid(self, rows, columns):
self.myCanvas = tk.Canvas(self.myContainer1)
self.myCanvas.configure(width=self.cellheight*rows+2,
height=self.cellwidth*columns+2)
self.myCanvas.pack(side=tk.RIGHT)
for column in range(rows):
for row in range(columns):
x1 = column * self.cellwidth+4
y1 = row * self.cellheight+4
x2 = x1 + self.cellwidth
y2 = y1 + self.cellheight
self.rect[row, column] = self.myCanvas.create_rectangle(x1, y1, x2, y2, fill="white")
def runApp(rows, columns):
root = tk.Tk()
myapp = GridWindow(root)
myapp.draw_grid(rows, columns)
root.mainloop()
if __name__ == '__main__':
runApp(10, 10)
现在看起来像这样:
所以我很感激,如果有人能解释我这种行为,或者我做错了什么,欢迎提出任何建议。
答案 0 :(得分:1)
我认为这个问题与坐标系包含边框所需的空间有关。也就是说,如果画布有边框并且您从0,0到0,100绘制一条线,那么该线将被边界透支。默认情况下,画布将具有一个或两个像素宽的边框。
尝试将borderwidth
和highlightthickness
属性设置为零,以便画布的完整宽度和高度可绘制。有了它,你不必在坐标上添加任何东西。
self.myCanvas.configure(borderwidth=0, highlightthickness=0)