为什么我的 Tkinter canvas 显示?

Why is my Tkinter canvas displaying?

我正在尝试使用 Tkinter 2d 图形用户界面生成星形算法。我已经修改了最初在这里找到的以下代码:

from tkinter import *

class CellGrid(Canvas):
    def __init__(self,master, rowNumber, columnNumber, cellSize, theMap):
        Canvas.__init__(self, master, width = cellSize * columnNumber , height = cellSize * rowNumber)

        self.cellSize = cellSize

        self.grid = []
        for row in range(rowNumber):
            line = []
            for column in range(columnNumber):
                line.append(Cell(self, column, row, cellSize, theMap[row][column]))
            self.grid.append(line)

        print (self.grid[0][0].value)
        self.draw()

    def draw(self):
        for row in self.grid:
            for cell in row:
                cell.draw()

class Cell():
    colors = {
            0: 'white',    # untried
            1: 'black',    # obstacle
            2: 'green',    # start
            3: 'red',      # finish
            4: 'blue',     # open
            5: 'gray',     # closed
            6: 'orange',   # path
         }

    def __init__(self, master, x, y, size, value):
        self.master = master
        self.abs = x
        self.ord = y
        self.size= size
        self.fill = "white"
        self.value = value


    def setValue(self, value):
        self.value = value

    def draw(self):
         if self.master != None :
            if self.value == 0:
                self.fill = self.white
            elif self.value == 1:
                self.fill = self.black
            elif self.value == 2:
                self.fill = self.green
            elif self.value == 3:
                self.fill = self.red
            elif self.value == 4:
                self.fill = self.blue
            elif self.value == 5:
                self.fill = self.gray
            elif self.value == 6:
                self.fill = self.orange

            xmin = self.abs * self.size
            xmax = xmin + self.size
            ymin = self.ord * self.size
            ymax = ymin + self.size

            self.master.create_rectangle(xmin, ymin, xmax, ymax, fill = self.fill, outline = "black")

def main():
    Map = [
            [2, 0, 0, 0, 0],
            [0, 1, 1, 1, 1],
            [0, 1, 3, 0, 0],
            [0, 1, 1, 1, 0],
            [0, 0, 0, 0, 0],
          ]
    root = Tk()
    c = tk.Canvas(root, height=1000, width=1000, bg='white')
    my_gui = CellGrid(root, len(Map), len(Map[0]), 40, Map)


    root.mainloop()

但是当我转到 运行 它时,没有任何显示。

很多小的和不小的误会阻碍了明星算法的展示.

问题 1 - 未完成调用 main() 函数。

As @avysk suggests as comment, the first blocking point is due to the missing of main() preamble in Python.

只需在def main()函数后添加如下代码即可:

if __name__ == '__main__':
    main()

问题 2 - 拼写错误并缺少 pack() 到主 Canvas 显示。

由于tk符号未定义,主要Canvas声明如下:

c = Canvas(root, height=1000, width=1000, bg='white')

而不是:

c = tk.Canvas(root, height=1000, width=1000, bg='white')

并且在魔法缺失调用之后是pack():

c.pack() # magic call to display the (1000 x 1000) white canvas

问题 3 - 缺少对辅助 Canvas 显示的调用。

至于主Canvas,缺少pack()的调用,有两种可能显示副Canvas

  1. 添加 my_gui.pack() 以适应主要 Canvas 到次要 Canvas 的大小,
  2. 或者我的首选解决方案,添加 my_gui.place(relx=0.5, rely=0.5, anchor=CENTER) 使辅助 Canvas 居中到主要 Canvas

显示副Canvas:

my_gui = CellGrid(c, len(Map), len(Map[0]), 40, Map)
my_gui.place(relx=0.5, rely=0.5, anchor=CENTER)

问题 4 - 对 Cell::draw() 函数中字典使用的误解。

The displayed error is "AttributeError: 'Cell' object has no attribute 'green'".

第一个单元格的值 self.grid[0][0].value = 2 和绘制单元格时,以下 self.fill = self.green 产生错误。

可以使用三种可能性来解决该错误:

  1. self.fill = self.<color>(7 例)替换为 self.fill = '<color>'
  2. 使用声明的字典 colors 并通过唯一调用替换 7 个案例。

字典的使用可以是 (sol 2):

if 0 <= self.value <= 6: # check if value in range of colors
    self.fill = Cell.colors[self.value]

而不是长 if-elif (sol 1):

    if self.value == 0:
        self.fill = 'white' # Error: self.white
    elif self.value == 1:
        self.fill = 'black' # Error: self.black
    elif self.value == 2:
        self.fill = 'green' # Error: self.green
    elif self.value == 3:
        self.fill = 'red' # Error: self.red
    elif self.value == 4:
        self.fill = 'blue' # Error: self.blue
    elif self.value == 5:
        self.fill = 'gray' # Error: self.gray
    elif self.value == 6:
        self.fill = 'orange' # Error: self.orange