python - 在 Python tkinter Canvas 上删除线条

标签 python tkinter tkinter-canvas

我试图让用户在单击鼠标右键时删除行。我已将按钮 3 按下事件绑定(bind)到 Canvas ,并将其传递给以下函数

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)

但是当我右键单击这些行时没有任何反应。我单独测试了字典,行对象存储正确。

这是我的绑定(bind):

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

字典在这里打印得很好。 请注意,这些都是一个类中的所有函数。

最佳答案

我已经尝试根据您的代码制作一个工作示例,现在我知道问题出在哪里:如果找到一项,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)

关于python - 在 Python tkinter Canvas 上删除线条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15436276/

相关文章:

python - 拖动 Canvas 时获取当前值

python - 使用 python 3 和 tkinter 中的 colorchooser 更改 tkinter 窗口的背景颜色

Python bind - 允许同时按下多个键

python - Tkinter 中滚动条不移动图像

python-3.x - Tkinter Canvas ,删除图像

python - 阻止 pygame 更改光标

python - 编写集成高斯函数的 Python 函数的最佳方法?

python - 滚动条在 python tkinter 中不起作用

python - Python 查找和替换脚本中的正则表达式?更新

python - 我如何在运行时编写 Python 文件?