我正在使用 tkinter 作为我的可视化工具在 python 2.7 中运行生物模拟器。地图由正方形组成,颜色代表土地类型,红色正方形代表生物。我使用 canvas.move 在棋盘上移动那个红色方块。它必须移动很多。但我确切地知道它应该从哪里开始,它应该在哪里结束。问题是,大多数时候它并没有移动,而是消失了。在下面的代码中,我在 Simulation 的 init 中调用 move,它可以工作。当我在 sim.simulate 中随时调用它时,这个生物就会消失。谁能解释为什么?
class Map():
def __init__(self,):
self.root = Tk()
self.canvas = Canvas(self.root, width=1200, height=1200)
self.canvas.pack()
self.colors = {
"Land": "grey",
"Food": "green",
"Water": "blue",
"Shelter": "black"
}
self.canvasDict = {} # the keys are (x,y, "type"), the data is the id so it can be grabbed for item config.
for i, row in enumerate(land.landMass):
for j, tile in enumerate(row):
color = self.colors[tile.__class__.__name__]
self.canvasDict[i, j, "tile"] = self.canvas.create_rectangle(50 * i, 50 * j, 50 * (i + 1), 50 * (j + 1),
outline=color, fill=color)
info = tile.elevation
if color == "green":
info = tile.vegitation
elif color == "black":
info = tile.quality
self.canvasDict[i, j, "text"] = self.canvas.create_text(50 * i + 3, 50 * j, anchor=NW, fill="white", text=info)
self.canvasDict["creature"] = self.canvas.create_rectangle(0, 0, 50, 50,
outline="red", fill="red")
self.canvas.pack(fill=BOTH, expand=1)
sim = Simulation([], 1, 2, self.root, self.canvas, self.canvasDict)
self.root.after(1000, sim.simulate)
... 其他功能 ...
def simulate(self):
self.canvas.move(self.canvasDict["creature"], 1, 1)
if self.generations > 0:
self.root.after(10000, self.canvas.move, self.canvasDict["creature"], 2 * 50, 2 * 50)
...