尝试从Tkinter Canvas中删除项目时出错

时间:2012-05-12 19:47:59

标签: python tkinter

当我想要关闭应用程序时,我收到以下错误:

Exception _tkinter.TclError: 'invalid command name ".47045488"' in <bound method
RootJoint.__del__ of <skeleton.RootJoint object at 0x0000000002CDDBA8>> ignored

以下是RootJoint的相关部分:

def __init__(self, canvas):
    self.parent = None
    self.angle = 0.0
    self.distance = 0.0

    topleft = 0 - Joint.SQUARE_HALF_SIDE, 0 + Joint.SQUARE_HALF_SIDE
    bottomright = 0 + Joint.SQUARE_HALF_SIDE, 0 - Joint.SQUARE_HALF_SIDE

    self._joint = canvas.create_rectangle(*(topleft + bottomright))
    canvas.itemconfig(self._joint, fill=RootJoint.COLOR_NORMAL)

    self.canvas = canvas

def __del__(self):
    self.canvas.delete(self._joint)

这就是创建画布和根关节的地方:

def main():
    root = tk.Tk()
    root.geometry('640x480')

    canvas = tk.Canvas(root)
    canvas.pack(fill=tk.BOTH, expand=True)

    rootjoint = skeleton.RootJoint(canvas)

    root.mainloop()

为什么会出现此错误以及如何解决?

1 个答案:

答案 0 :(得分:1)

问题在于

del

当对canves的最后一次引用丢失并删除该对象时,将调用

你想要的是

def __init__(...):
    ...
    self.bind("<Destroy>", self.onDestroy)
def onDestroy(self, event):
    self.canvas.delete(self._joint)

首先将画布和所有元素销毁并销毁然后删除