删除对象的实例

2024-09-29 06:34:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图理解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的一个实例,但它不会在右键单击时删除对象:

^{pr2}$

Tags: self程序objapplicationinitdefcreatebutton
1条回答
网友
1楼 · 发布于 2024-09-29 06:34:35

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

相关问题 更多 >