Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # xy_line_dist.py
- # Python program to find the distance between
- # a given point and a given line in 2D.
- from Tkinter import *
- import math
- def XY(X,Y,r=50):
- return X-r,Y-r,X+r,Y+r
- 0
- def dist(objA,objB):
- x1,y1 = objA
- x2,y2 = objB
- abs(x1-x2)+abs(y1-y2)
- return math.sqrt((x1-x2)**2+(y1-y2)**2)
- 0
- def linetrack(segment, x2,y2, r=50,line_thickness=4): # x,y is the point
- xmin,ymin,xmax,ymax = segment
- w = abs(xmax-xmin)
- h = abs(ymax-ymin)
- if w>h:
- p = (x2-xmax+w)*1.0/w
- else:
- p = 1-(y2-ymax+h)*1.0/h
- y = ymin-(h*p)
- x = xmin+(w*p)
- x = max(xmin,min(xmax,x))
- y = max(ymax,min(ymin,y))
- canvas.coords(target,XY(x,y,5))
- d = dist((x,y),(x2,y2))
- if d > r + line_thickness:
- canvas.itemconfigure('circle',fill="red")
- else:
- canvas.itemconfigure('circle',fill="green")
- 0
- def Click(event):
- X = event.x
- Y = event.y
- xmin,ymin,xmax,ymax = cv.xy
- cv.onTarget = False
- if xmin<X<xmax and ymin<Y<ymax: cv.onTarget = True
- 0
- def Drag(event):
- X = event.x
- Y = event.y
- if cv.onTarget == True:
- if X<0: X=0
- elif X>L: X=L
- if Y<0: Y=0
- elif Y>H: Y=H
- cv.xy = XY(X,Y)
- linetrack(theline, X,Y)
- canvas.coords(circle,cv.xy)
- 0
- root = Tk()
- root.title("XY Line Distancing")
- class Cv(): 0
- cv = Cv()
- cv.onTarget = False
- L = 1000
- H = 500
- theline = [200,360,800,160]
- cv.xy = XY(100,100)
- canvas = Canvas(root,width=L,height=H,bg ='white')
- circle = canvas.create_oval(cv.xy,tags='circle',fill='red')
- canvas.create_line(theline,width=3,fill='gray')
- target = canvas.create_oval(XY(L/2,H/2,5),fill='black')
- canvas.bind('<Button-1>',Click)
- canvas.bind('<B1-Motion>',Drag)
- canvas.focus_set()
- canvas.pack(padx=10,pady=10)
- root.mainloop()
- #
Add Comment
Please, Sign In to add comment