I've already asked a similar question here and I received quite a helpful reply. But since then I've modified my code, now it is more optimized I guess, it is supposed to be more flexible, but the same problem persists. I can not delete an instance of the class.
What I'm trying to do is to create a circle (on a left-click) and then I expect the program to delete the circle (on a right-click).
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()
so, once again, the problem is that here I can not delete the object:
def delete_obj(self, event):
self.can1.delete(self.d)
One more question. Given the fact that I'm just a begginer I don't know if I chose the right approach as far as class organisation is concerned. Does it look like a well-organized code or should I change anything at this stage already?
These two lines:
self.d = Oval()
self.can1.create_oval(self.d.x1, self.d.y1, self.d.x2, self.d.y2, fill='red', width = 2)
create a new Oval
object, assign that object to the name self.d
, then create an oval on self.can1
that is completely unrelated (aside from having the same dimensional attributes) from the Oval
object assigned to self.d
. Instead, I think you want:
o = Oval()
self.d = self.can1.create_oval(o.x1, o.y1, o.x2, o.y2, fill='red', width = 2)
This retains a reference to the object on the Canvas
, so you will be able to delete
it. Note that Oval
is more-or-less-completely pointless, as all it does is provide the dimensions.