I am trying to delete mouse-created circles with the right button. I also want to delete each circle separately. I modify my code with this answer ( https://stackoverflow.com/a/65174542/13560126 ) to create circles but however when I try to delete each of them, I always getting an error. Here is the code:
import tkinter as tk
from functools import partial
class DrawCircles(tk.Canvas):
def __init__(self, master=None, **kwargs):
super().__init__(master, **kwargs)
image = self.create_rectangle(0, 0, 300, 300, width=4, fill='grey')
self.tag_bind(image, '<Button-1>', self.on_click)
self.tag_bind(image, '<Button1-Motion>', self.on_motion)
self.tag_bind(image, '<Button-3>', self.delete)
def delete(self):
super().delete('all')
def on_click(self, event):
self.start = event.x, event.y
self.current = self.create_oval(*self.start, *self.start, width=5,outline='yellow')
self.tag_bind(self.current, '<Button-1>', partial(self.on_click_circle, self.current))
self.tag_bind(self.current, '<Button1-Motion>', self.on_motion)
def on_click_circle(self, tag, event):
self.current = tag
x1, y1, x2, y2 = self.coords(tag)
if abs(event.x-x1) < abs(event.x-x2):
x1, x2 = x2, x1
if abs(event.y-y1) < abs(event.y-y2):
y1, y2 = y2, y1
self.start = x1, y1
print(x1,y1,x2,y2)
def on_motion(self, event):
self.coords(self.current, *self.start, event.x, event.y)
def on_move(self,event):
component = self.current
x1, y1, x2, y2 = self.coords(component)
locx, locy = component.winfo_x(), component.winfo_y()
mx ,my =component.winfo_width(),component.winfo_height()
xpos=(locx+event.x)-int(mx/2)
ypos=(locy+event.y)-int(my/2)
if xpos>=0 and ypos>=0:
component.place(x=xpos,y=ypos)
if __name__ == '__main__':
main = DrawCircles()
main.pack()
main.mainloop()
Error:
delete() takes 1 positional argument but 2 were given
Your delete()
function, gets called on pressing 'Button-3', ie, it is triggered as an event to the canvas, so it takes in an extra parameter(like e
or event
or whatever), which you are not passing.
So EITHER pass e
during function call OR define e
as a parameter during function definition.
self.tag_bind(image, '<Button-3>', lambda e: self.delete()) # Same as event or any_var_name_at_all
Or
def delete(self,event): # Same as e or any_var_name_at_all
super().delete('all')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.