here2share

# xy_line_dist.py

Nov 13th, 2018 (edited)
350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.69 KB | None | 0 0
  1. # xy_line_dist.py
  2.  
  3. # Python program to find the distance between
  4. # a given point and a given line in 2D.
  5.  
  6. from Tkinter import *
  7. import math
  8.  
  9. def XY(X,Y,r=50):
  10.     return X-r,Y-r,X+r,Y+r
  11. 0
  12. def dist(objA,objB):
  13.     x1,y1 = objA
  14.     x2,y2 = objB
  15.     abs(x1-x2)+abs(y1-y2)
  16.     return math.sqrt((x1-x2)**2+(y1-y2)**2)
  17. 0
  18. def linetrack(segment, x2,y2, r=50,line_thickness=4): # x,y is the point
  19.     xmin,ymin,xmax,ymax = segment
  20.     w = abs(xmax-xmin)
  21.     h = abs(ymax-ymin)
  22.     if w>h:
  23.         p = (x2-xmax+w)*1.0/w
  24.     else:
  25.         p = 1-(y2-ymax+h)*1.0/h
  26.     y = ymin-(h*p)
  27.     x = xmin+(w*p)
  28.     x = max(xmin,min(xmax,x))
  29.     y = max(ymax,min(ymin,y))
  30.     canvas.coords(target,XY(x,y,5))
  31.     d = dist((x,y),(x2,y2))
  32.    
  33.     if d > r + line_thickness:
  34.         canvas.itemconfigure('circle',fill="red")
  35.     else:
  36.         canvas.itemconfigure('circle',fill="green")
  37. 0
  38. def Click(event):
  39.     X = event.x
  40.     Y = event.y
  41.     xmin,ymin,xmax,ymax = cv.xy
  42.     cv.onTarget = False
  43.     if xmin<X<xmax and ymin<Y<ymax: cv.onTarget = True
  44. 0
  45. def Drag(event):
  46.     X = event.x
  47.     Y = event.y
  48.     if cv.onTarget == True:
  49.         if X<0: X=0
  50.         elif X>L: X=L
  51.         if Y<0: Y=0
  52.         elif Y>H: Y=H
  53.         cv.xy = XY(X,Y)
  54.        
  55.         linetrack(theline, X,Y)
  56.         canvas.coords(circle,cv.xy)
  57. 0
  58. root = Tk()
  59. root.title("XY Line Distancing")
  60.  
  61. class Cv(): 0
  62. cv = Cv()
  63. cv.onTarget = False
  64.  
  65. L = 1000
  66. H = 500
  67. theline = [200,360,800,160]
  68. cv.xy = XY(100,100)
  69.  
  70. canvas = Canvas(root,width=L,height=H,bg ='white')
  71. circle = canvas.create_oval(cv.xy,tags='circle',fill='red')
  72. canvas.create_line(theline,width=3,fill='gray')
  73. target = canvas.create_oval(XY(L/2,H/2,5),fill='black')
  74.  
  75. canvas.bind('<Button-1>',Click)
  76. canvas.bind('<B1-Motion>',Drag)
  77.  
  78. canvas.focus_set()
  79. canvas.pack(padx=10,pady=10)
  80.  
  81. root.mainloop()
  82. #
Add Comment
Please, Sign In to add comment