0

现在我在土地类中有下面的代码来打印游戏板。有一个单独的类来保存游戏动作,因此每次游戏中发生某些事情时都会调用此函数。在这一点上,该类构建了一个新的画布,并且每次都一遍又一遍地破坏旧的画布。有没有办法让它简单地更新画布而不是破坏它。

def printBoard(self):
        master = Tk()

        w = Canvas(master, width=503, height=503)
        w.pack()
        for x, row in enumerate(self.a):
            for y, cell in enumerate(row):
                if self.a[x][y][1] == 'C':
                    w.create_rectangle([3 + 50 * y, 3 + 50 * x, 53 + 50 * y, 53 + 50 * x ], fill="black")
                    w.create_text(3 + 50 * y, 3 + 50 * x, anchor=NW, fill="white", text=self.a[x][y][0][1])
                else:
                    if self.a[x][y][0][0] == 'f':     
                        w.create_rectangle([3 + 50 * y, 3 + 50 * x, 53 + 50 * y, 53 + 50 * x ], fill="green")
                        w.create_text(3 + 50 * y, 3 + 50 * x, anchor=NW, fill="white", text=self.a[x][y][0][1])
                    elif self.a[x][y][0][0] == 'w':
                        w.create_rectangle([3 + 50 * y, 3 + 50 * x, 53 + 50 * y, 53 + 50 * x ], fill="blue")
                        w.create_text(3 + 50 * y, 3 + 50 * x, anchor=NW, fill="white", text=self.a[x][y][0][1])
                    elif self.a[x][y][0][0] == 'X':
                        w.create_rectangle([3 + 50 * y, 3 + 50 * x, 53 + 50 * y, 53 + 50 * x ], fill="brown")
                        w.create_text(3 + 50 * y, 3 + 50 * x, anchor=NW, fill="white", text=self.a[x][y][0][1])
                    elif self.a[x][y][0][0] == 's':
                        w.create_rectangle([3 + 50 * y, 3 + 50 * x, 53 + 50 * y, 53 + 50 * x ], fill="gray")
                        w.create_text(3 + 50 * y, 3 + 50 * x, anchor=NW, fill="white", text=self.a[x][y][0][1])
        master.after(1000, lambda: master.destroy())
        master.mainloop()
4

1 回答 1

2

是的,您可以在创建画布项目时存储它们的 ID,因此它们可用于通过coords方法更新其位置并itemconfig更改选项(如填充颜色)。

# Create
self.ids[x][y] = w.create_rectangle([3 + 50 * y, ...)

# Update
fillcolors = {'f':'green', 'w':'blue', 'X':'brown', 's':'gray'}
fill = "black" if self.a[x][y][1] == 'C' else fillcolors[self.a[x][y][0][0]]
w.coords(self.ids[x][y], [3 + 50 * y, ...)
w.itemconfig(self.ids[x][y], fill=fill)

请注意,有很多重复的代码,因此您可以使用已经映射颜色的辅助字典,然后避免嵌套条件。

于 2013-03-12T02:45:04.813 回答