我可以跟踪用户点击的位置以及他们发布的位置,但我想跟踪行进的距离。
来自Tkinter进口* root = Tk()
类DragCursor():
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()
答案 0 :(得分:3)
您只需使用距离公式来确定xy平面中两点之间的距离,
此外,您需要包含某种实例变量,它将保存起点和终点的坐标,以便您可以在鼠标释放后计算它。
这几乎是您的代码,只需使用distancetraveled
使用StopMove
打印在self.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()
函数。
{{1}}