2013-05-01 52 views
0

我可以跟蹤這些用戶的點擊和他們釋放,但我想跟蹤行駛距離。如何找到行駛距離的Tkinter ButtonPress

從Tkinter的進口* 根= 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

你的代碼示例的縮進被搞砸了。 – 2013-05-01 11:26:42

回答

3

你只需要使用距離公式用於確定的XY平面上的兩個點之間的距離,

Distance Formula Wikipedia

此外,您還需要包括某種形式的實例變量,將節省的座標的開始和結束點,以便您可以在鼠標釋放後進行計算。

這幾乎是你的代碼,只是在StopMove的末尾使用self.positions打印了一個新的distancetraveled函數。

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() 
+0

歐幾里德幾何的+1! – 2013-05-01 05:58:10