【问题标题】:How To Delete Previously Drawn Line With a Mouse Click in Python?如何在 Python 中通过鼠标单击删除先前绘制的线?
【发布时间】:2013-09-25 21:37:58
【问题描述】:

我想通过鼠标点击删除使用 Tkinter/Python 在画布上绘制的线条。

此代码将线绘制为对象,然后立即将其删除:

#!/usr/bin/python
from Tkinter import *

master = Tk()
w = Canvas(master, width=200, height=200)
w.pack()
i=w.create_line(0, 0, 100, 100)
w.delete(i)

mainloop()

在鼠标单击时删除行的代码是什么(左键或右键无关紧要)?

谢谢。

【问题讨论】:

    标签: python python-2.7 python-3.x tkinter


    【解决方案1】:

    这样就可以了:

    from Tkinter import *
    
    master = Tk()
    w = Canvas(master, width=200, height=200)
    w.pack()
    i=w.create_line(0, 0, 100, 100)
    
    # Bind the mouse click to the delete command
    w.bind("<Button-1>", lambda e: w.delete(i))
    
    mainloop()
    

    根据评论进行编辑

    是的,上述解决方案将在窗口中的任意位置注册鼠标单击。如果您希望它仅在单击靠近它时删除该行,您将需要更复杂的东西。也就是说,像这样:

    from Tkinter import *
    
    master = Tk()
    w = Canvas(master, width=200, height=200)
    w.pack()
    i=w.create_line(0, 0, 100, 100)
    
    def click(event):
        # event.x is the x coordinate and event.y is the y coordinate of the mouse
        if 80 < event.x < 120 and 80 < event.y < 120:
            w.delete(i)
    
    w.bind("<Button-1>", click)
    
    mainloop()
    

    只有当鼠标点击的xy坐标在直线的20点以内时,这个脚本才会删除直线。

    请注意,我不能完美地设置它。您必须根据自己的需要对其进行调整。

    【讨论】:

    • 我注意到当鼠标指针离线很远(一英寸左右)时,这也会删除线。当指针靠近它时,有没有办法删除该行?
    • @Platypus - 您可以获取鼠标单击的 x 和 y 坐标,然后仅当它们在该线的一定距离内时才删除该线。查看我的编辑。
    • 不幸的是,这只适用于行尾的方形区域。 20点区域并没有沿着线一直跟随。我认为必须有一个以某种方式编程的线方程。
    • 需要注意沿线的点以及端点。涉及到一点几何。最后,我的代码适用于给定的线段。如果只考虑整条线而不是线段,则可以省略端点检查。
    【解决方案2】:
    from Tkinter import *
    import math
    
    master = Tk()
    w = Canvas(master, width=200, height=200)
    w.pack()
    x1=0
    y1=0
    x2=100
    y2=100
    delta=10
    i=w.create_line(x1, y1, x2, y2)
    
    def click(event):
    # event.x is the x coordinate and event.y is the y coordinate of the mouse
        D = math.fabs((event.y-event.x))/math.sqrt(2)    
        if D < delta and x1 - delta < event.x < x2 + delta:
                w.delete(i)    
    w.bind("<Button-1>", click)
    
    mainloop()
    

    【讨论】:

      猜你喜欢
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-30
      • 2023-03-31
      • 2017-07-14
      • 2013-04-14
      • 1970-01-01
      相关资源
      最近更新 更多