单击鼠标后停止画布形状跟随光标

问题描述

我正在制作一个 GUI 来使用 Tkinter 绘制加权图,所以我制作了一个按钮,单击该按钮时会使用画布创建一个圆(图形顶点)。那么圆圈应该跟随光标移动到画布上的任何位置,并在鼠标点击时停止。

我设法让圆圈跟随光标,但我不知道如何让它停止跟随。

这是我做的功能

def buttonClick():
    def Mouse_move(event):
        x,y = event.x,event.y
        canvas.moveto(vertex,x,y )

    vertex= canvas.create_oval(650,100,750,200)
    canvas.bind("<Motion>",Mouse_move)

解决方法

可以在回调中绑定鼠标点击事件<Button-1>和解除绑定<Motion>事件:

def buttonClick():
    def mouse_move(event):
        x,y = event.x,event.y
        canvas.moveto(vertex,x,y)

    def mouse_click(event):
        canvas.unbind("<Motion>")

    vertex = canvas.create_oval(650,100,750,200)
    canvas.bind("<Motion>",mouse_move)
    canvas.bind("<Button-1>",mouse_click)