删除类的实例

0 投票
1 回答
2607 浏览
提问于 2025-04-28 02:58

我之前在这里问过一个类似的问题,得到了很有帮助的回复。 不过自那以后我修改了我的代码,现在我觉得它更优化了,应该更灵活,但同样的问题还是存在。我无法删除这个类的实例。

我想做的是在左键点击时创建一个圆圈,然后我希望程序在右键点击时删除这个圆圈。

My code:

from tkinter import *

class Application:
    def __init__(self):
        self.fen = Tk()
        self.fen.title('Rom-rom-roooooom')
        self.butt1 = Button(self.fen, text = ' Quit ', command = self.fen.quit)
        self.can1 = Canvas(self.fen, width = 300, height = 300, bg = 'ivory')
        self.can1.grid(row = 1)
        self.butt1.grid(row = 2)
        self.fen.bind("<Button-1>", self.create_obj)
        self.fen.bind("<Button-3>", self.delete_obj)
        self.fen.mainloop()
    def create_obj(self, event):
        self.d = Oval()
        self.can1.create_oval(self.d.x1, self.d.y1, self.d.x2, self.d.y2, fill='red', width = 2)
    def delete_obj(self, event):
        self.can1.delete(self.d)


class Oval:

    def __init__(self):
        self.x1 = 50
        self.y1 = 50
        self.x2 = 70
        self.y2 = 70



appp = Application()

所以,再次说一下,问题是我无法删除这个对象:

def delete_obj(self, event):
        self.can1.delete(self.d)

还有一个问题。考虑到我只是个初学者,我不知道我在类的组织上是否选择了正确的方法。看起来像是一个结构良好的代码吗?还是我在这个阶段就应该更改一些东西?

暂无标签

1 个回答

1

这两行代码:

self.d = Oval()
self.can1.create_oval(self.d.x1, self.d.y1, self.d.x2, self.d.y2, fill='red', width = 2)

创建了一个新的 Oval 对象,并把这个对象命名为 self.d。然后在 self.can1 上又创建了一个椭圆,这个椭圆和 self.d 里的 Oval 对象完全没有关系(除了它们的尺寸属性是一样的)。其实,你可能想要的是:

o = Oval()
self.d = self.can1.create_oval(o.x1, o.y1, o.x2, o.y2, fill='red', width = 2)

这样做可以保留对画布上这个对象的引用,这样你就可以用 delete 来删除它。需要注意的是,Oval 这个东西几乎是没什么用的,因为它只提供了尺寸信息。

撰写回答