0

我可以跟踪用户单击的位置和释放的位置,但我想跟踪行进的距离。

从 Tkinter 导入 * root = Tk()

类拖动光标():

def __init__(self, location):
    self.label = location
    location.bind('<ButtonPress-1>', self.StartMove)
    location.bind('<ButtonRelease-1>', self.StopMove)


def StartMove(self, event):
    startx = event.x
    starty = event.y
    print [startx, starty]

def StopMove(self, event):
    self.StartMove
    stopx = event.x
    stopy = event.y
    print [stopx, stopy]



location = Canvas(root, width = 300, height = 300)
DragCursor(location)
location.pack()
root.mainloop()
4

1 回答 1

3

您只需要使用距离公式来确定 xy 平面中两点之间的距离,

距离公式维基百科

此外,您需要包含某种实例变量来保存起点和终点的坐标,以便您可以在释放鼠标后计算它。

这几乎是您的代码,只是在使用结束时打印了一个新distancetraveled函数。StopMoveself.positions

from Tkinter import *

root = Tk()

class DragCursor():
    def __init__(self, location):
        self.label = location
        location.bind('<ButtonPress-1>', self.StartMove)
        location.bind('<ButtonRelease-1>', self.StopMove)
        self.positions = {}

    def StartMove(self, event):
        startx = event.x
        starty = event.y
        self.positions['start'] = (startx, starty)

    def StopMove(self, event):
        stopx = event.x
        stopy = event.y
        self.positions['stop'] = (stopx, stopy)
        print self.distancetraveled()

    def distancetraveled(self):
        x1 = self.positions['start'][0]
        x2 = self.positions['stop'][0]
        y1 = self.positions['start'][1]
        y2 = self.positions['stop'][1]
        return ((x2-x1)**2 + (y2-y1)**2)**0.5

location = Canvas(root, width = 300, height = 300)
DragCursor(location)
location.pack()
root.mainloop()
于 2013-05-01T05:44:01.373 回答