Advertisement
here2share

# polygon_edit.py

Nov 13th, 2018
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.55 KB | None | 0 0
  1. # polygon_edit.py
  2.  
  3. from Tkinter import *
  4. #Tk()
  5.  
  6. import sys
  7.  
  8. root = Tk()
  9. R = 10
  10. p = []
  11. history = []
  12.  
  13. def f_redraw():
  14.     w.delete(ALL)
  15.     for i in range(len(p)):
  16.         j = (i + 1) % len(p)
  17.         w.create_line(p[i][0], p[i][1], p[j][0], p[j][1], fill="red")
  18.     # enumerate([x, y, z]) = [(0, x), (1, y), (2, z)]
  19.     for i, (x, y) in enumerate(p):
  20.         w.create_oval(x - R, y - R, x + R, y + R,
  21.             fill="green", outline="#00aa00")
  22.         w.create_text(x, y, fill="white",
  23.             text=str(i+1), justify=CENTER, font="Courier 10 bold")
  24.    
  25. def f_key(event):
  26.     c = repr(event.char)
  27.     print("pressed key {0} {1}".format(c, event.char))
  28.     if event.char == 'q':
  29.         sys.exit(0)
  30.  
  31. def dist(a, b):
  32.     return (a[0]-b[0])**2 + (a[1]-b[1])**2
  33. def f_delete(event):
  34.     print("clicked-2 at", event.x, event.y)
  35.     global p
  36.     if len(p) == 0:
  37.         return
  38.     pos = (event.x, event.y)
  39.     i = 0
  40.     for j in range(len(p)):
  41.         if dist(pos, p[j]) < dist(pos, p[i]):
  42.             i = j
  43.     history.append(list(p))
  44.     p = p[:i] + p[i+1:]
  45.     f_redraw()
  46.  
  47. def f_cancel(event):
  48.     global p, history
  49.     print("cancel: len(history) = %d" % len(history))
  50.     if len(history) > 0:
  51.         p = history[-1]
  52.         history = history[:-1]
  53.     f_redraw()
  54.  
  55. def f_button(event):
  56.     print("clicked-1 at", event.x, event.y)
  57.     global R, history, p
  58.     w.focus_set()
  59.     history.append(list(p))
  60.     p.append((event.x, event.y))
  61.     f_redraw()
  62.  
  63. w = Canvas(root, width=400, height=400)
  64. w.focus_set()
  65. w.bind("<Key>", f_key)
  66. w.bind("<Control-z>", f_cancel)
  67. w.bind("<Control-Z>", f_cancel)
  68. w.bind("<Button-1>", f_button)
  69. w.bind("<Button-3>", f_delete)
  70. w.pack()
  71.  
  72. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement