删除对象的实例

时间:2014-10-14 14:37:54

标签: python object instance sleep

我正在尝试理解Python中的类概念,并决定做一些我发现自己面临问题的练习。

我要做的是创建一个圆圈(左键单击),然后我希望程序删除圆圈(右键单击)。

嗯,这是问题的第二部分。

我的代码:

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()

这里,程序理解'd'是类Oval的一个实例,但它不会在右键单击时删除该对象:

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

1 个答案:

答案 0 :(得分:2)

从tkinter文档中,create_oval返回一个对象id,它是一个整数。要删除圈子,请使用Canvas.delete方法:

from tkinter import *

import time

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.mainloop()

    def create_obj(self, event):
        d = self.can1.create_oval(150,150, 170, 170, fill='red', width = 2)
        time.sleep(3)
        self.can1.delete(d)

appp = Application()