在Python tkinter画布上删除线条
我正在尝试让用户在右键点击时删除某些线条。我已经把鼠标右键按下的事件绑定到了画布上,并把这个事件传递给了下面的函数。
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)
但是当我右键点击这些线条时,什么也没有发生。我单独测试过字典,线条对象也确实被正确存储了。
这是我的绑定代码:
self.workspace.bind("<Button-3>", self.eraseItem)
应要求,这里还有一些字典初始化的其他代码片段。
def __init__(self, parent):
self.dictID = {}
... Some irrelevant code omitted
在创建线条时,我有两个处理程序,一个是点击时的,另一个是松开时的,这样就可以在两个坐标之间画出线条。
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
字典在这里打印得很好。请注意,这些都是同一个类里的函数。
1 个回答
0
我根据你的代码做了一个可以运行的例子,现在我知道问题出在哪里了:find_closest
函数如果找到了一个项目,会返回一个包含一个元素的元组。所以当你检查这个元组是否在字典里时,首先得取出元组里的第一个元素。
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)