【问题标题】:tkinter's canvas.move makes object disappeartkinter canvas.move 使对象消失
【发布时间】:2013-07-24 23:22:48
【问题描述】:

我在 python 2.7 中运行一个生物模拟器,使用 tkinter 作为我的可视化工具。地图由正方形组成,颜色代表土地类型,红色正方形代表生物。我使用 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)
            ...

【问题讨论】:

    标签: python python-2.7 tkinter


    【解决方案1】:

    我终于意识到发生了什么。我错误地认为.move 会将对象移动到画布上的那个位置,而不是移动它那么多。因此,当我的正方形“消失”时,它实际上只是在移动可见的画布。我以为.after 会停止动作,以便我可以看到这种情况发生,但显然不是。

    【讨论】:

      猜你喜欢
      • 2017-02-14
      • 2015-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-20
      • 1970-01-01
      • 2010-09-05
      相关资源
      最近更新 更多