简体   繁体   English

为什么我的Tkinter画布显示?

[英]Why is my Tkinter canvas displaying?

I am trying to produce a star algorithm using Tkinter 2d graphical user interface. 我正在尝试使用Tkinter 2d图形用户界面生成一种星形算法。 I have modified the following code having found it originally on here: 我修改了下面的代码,这些代码最初是在这里找到的:

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

But when I go to run it, nothing displays. 但是当我运行它时,什么也没有显示。

A lot of small and not-small misunderstandings are blocking the display of the star algorithm . 许多小的和不小的误解阻碍了star算法的显示。

Problem 1 - incomplete calling main() function. 问题1-调用main()函数不完整。

As @avysk suggests as comment, the first blocking point is due to the missing of main() preamble in Python. 正如@avysk建议的那样,第一个阻塞点是由于Python中缺少main()前言所致。

Just add the following code after the def main() function: 只需在def main()函数之后添加以下代码:

if __name__ == '__main__':
    main()

Problem 2 - typo and missing pack() to the main Canvas display. 问题2-错字和缺少Canvas主显示的pack()

Because the tk symbol is not defined, the main Canvas shall be declared as follow: 由于未定义tk符号,因此应将主Canvas声明如下:

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

Instead of: 代替:

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

And after the magic missing call is pack() : 在魔术丢失的电话之后是pack()

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

Problem 3 - missing call to the secondary Canvas display. 问题3-缺少对辅助Canvas显示的调用。

As for the main Canvas , it was missing the call of pack() , two possibilities could be used to display the secondary Canvas . 至于主要的Canvas ,它缺少对pack()的调用,可以使用两种可能性来显示辅助的Canvas

  1. Add my_gui.pack() to fit the main Canvas to the size of the secondary Canvas , 添加my_gui.pack()以使主Canvas适应辅助Canvas的大小,
  2. Or my preferred solution, add my_gui.place(relx=0.5, rely=0.5, anchor=CENTER) to center the secondary Canvas to the main Canvas . 或我的首选解决方案,添加my_gui.place(relx=0.5, rely=0.5, anchor=CENTER)以将辅助Canvas my_gui.place(relx=0.5, rely=0.5, anchor=CENTER)Canvas

To display the secondary Canvas : 要显示辅助Canvas

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

Problem 4 - misunderstanding of dictionary use in the Cell::draw() function. 问题4 –对Cell::draw()函数中的字典用法有误解。

The displayed error is " AttributeError: 'Cell' object has no attribute 'green' ". 显示的错误为“ AttributeError: 'Cell' object has no attribute 'green' “。

The value of the first cell self.grid[0][0].value = 2 and when drawing the cell, the following self.fill = self.green generates the error. 第一个单元格self.grid[0][0].value = 2并且在绘制单元格时,以下self.fill = self.green生成错误。

Three possibilities could be used to solve that error: 可以使用三种可能性解决该错误:

  1. Replace the self.fill = self.<color> (7 cases) by self.fill = '<color>' , self.fill = self.<color> (7种情况)替换为self.fill = self.<color> self.fill = '<color>'
  2. Use the declared dictionary colors and replace the 7 cases by a unique call. 使用声明的字典colors并通过唯一调用替换这7种情况。

The use of dictionary could be (sol 2): 字典的使用可能是(sol 2):

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

Instead of the long if-elif (sol 1): 代替长的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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM