我有一个模拟,创建在地图周围移动。地图是用 tkinter 绘制的。在模拟的初始化中,我调用
root = Tk()
root.geometry("800x800+300+300")
self.ex = land.Example(root)
root.mainloop()
启动 tkinter,其中 land.Example 是下面的类。应该发生的是最初绘制地图,然后模拟运行,并且每当生物移动时,它都会使用 self.ex 在 tkinter 中绘制它。问题是,当它运行时,地图是最初绘制的,我必须关闭它,以便模拟的其余部分运行。在那种情况下,整个事情都会中断,因为模拟试图使用不再存在的画布。我该如何解决这个问题,以便地图和模拟都保持运行
模拟 self.ex 交互
def move(self, creature, target):
self.map[creature.x][creature.y].creatures.remove(creature)
self.ex.updateMap(creature.x, creature.y, "remove")
土地.例子
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.parent.title("Board")
self.pack(fill=BOTH, expand=1)
self.canvas = Canvas(self)
self.upperX = 0
self.lowerX = 0
self.upperY = 0
self.lowerY = 0
for x, row in enumerate(landMass):
for y, cell in enumerate(row):
color = "grey"
if isinstance(landMass[x][y], Food):
color = "green"
elif isinstance(landMass[x][y], Water):
color = "blue"
elif isinstance(landMass[x][y], Shelter):
color = "black"
self.canvas.create_rectangle(50 * x , 50 * y , 50 * x + 50, 50 * y + 50,
outline=color, fill=color)
self.canvas.create_text(3 + 50 * x, 3 + 50 * y, anchor=NW, fill="white", text=landMass[x][y].elevation)
if color == "green":
self.canvas.create_text(3 + 70 * x, 3 + 50 * y, anchor=NE, fill="red", text=landMass[x][y].vegitation)
elif color == "black":
self.canvas.create_text(3 + 70 * x, 3 + 50 * y, anchor=NE, fill="orange", text=landMass[x][y].quality)
self.canvas.pack(fill=BOTH, expand=1)
def updateMap(self, x, y, action):
color = "grey"
if action == "append":
#DRAW THE CREATURE AT X,Y
elif action == "remove":
#DRAW THE ORIGINAL TILE AT X,Y
...
self.canvas.pack(fill=BOTH, expand=1)
编辑:其他尝试
当我将以下内容添加到 Simulation 的init () 并添加一个函数时。整个事情都在运行,但是 tk 画布显示的是最终结果,而不是正在发生的结果。
root = Tk()
root.geometry("800x800+300+300")
self.tkmap = land.Example(root)
root.after(2000, self.runSim)
root.mainloop()
#End of __init__()
def runSim(self):
for generation in range(self.lifeCycles):
self.simulate(generation)
return self.evolve()