Removing lines on a Python tkinter canvas

I am trying to have the user delete rows when right clicking. I linked the button 3 pressing the event to the canvas and passed it to the next function

def eraseItem(self,event): objectToBeDeleted = self.workspace.find_closest(event.x, event.y, halo = 5) if objectToBeDeleted in self.dictID: del self.dictID[objectToBeDeleted] self.workspace.delete(objectToBeDeleted) 

However, nothing happens when I right-click on a line. I tested the dictionary separately, and line objects are saved correctly.

Here is my binding:

 self.workspace.bind("<Button-3>", self.eraseItem) 

To query some other fragments from dictionary initialization

 def __init__(self, parent): self.dictID = {} ... Some irrelevant code omitted 

To create a line, I have two handlers: a click and a shutdown, which draws lines between both coordinates

 def onLineClick(self, event): self.coords = (event.x, event.y) def onLineRelease(self, event): currentLine = self.workspace.create_line(self.coords[0], self.coords[1], event.x, event.y, width = 2, capstyle = ROUND) self.dictID[currentLine] = self.workspace.coords(currentLine) print(self.dictID.keys()) #For testing dictionary population print(self.dictID.values()) #For testing dictionary population 

The dictionary prints great here. Please note that these are all functions within the same class.

+4
source share
1 answer

I tried to create a working example based on your code, and now I know where the problem is: find_closest returns a tuple with one element if an element is found, so when you check if it is in the dictionary, you should first get the first element of the tuple.

 def eraseItem(self,event): tuple_objects = self.workspace.find_closest(event.x, event.y, halo = 5) if len(tuple_objects) > 0 and tuple_objects[0] in self.dictID: objectToBeDeleted = tuple_objects[0] del self.dictID[objectToBeDeleted] self.workspace.delete(objectToBeDeleted) 
0
source

Source: https://habr.com/ru/post/1469550/


All Articles