Advertisement
here2share

# nearest_px2b.py

Feb 23rd, 2025
139
1
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.59 KB | None | 1 0
  1. # nearest_px2b.py
  2.  
  3. import tkinter as tk
  4. import math
  5.  
  6. grid_rows, grid_cols = 9, 9
  7. canvas_size = 600
  8. cell_w = canvas_size / grid_cols
  9. cell_h = canvas_size / grid_rows
  10. cx, cy = grid_rows // 2, grid_cols // 2
  11.  
  12. root = tk.Tk()
  13. root.title("# nearest_px2b.py")
  14. root.geometry(f"+10+10")
  15. canvas = tk.Canvas(root, width=canvas_size, height=canvas_size, bg='white')
  16. canvas.pack()
  17.  
  18. def nearest_px2b(x, y, x0, y0):
  19.     dx = x0 - x
  20.     dy = y0 - y
  21.     print(x, y, x0, y0)
  22.     length = math.sqrt(dx*dx + dy*dy)
  23.     if length == 0:
  24.         return (x, y)
  25.     step_x = int(round(dx / length))
  26.     step_y = int(round(dy / length))
  27.     neighbor = (x + step_x, y + step_y)
  28.     return neighbor
  29.  
  30. def get_cell_index(x, y):
  31.     col = int(x // cell_w)
  32.     row = int(y // cell_h)
  33.     col = min(grid_cols-1, col)
  34.     row = min(grid_rows-1, row)
  35.     return (col, row)
  36.  
  37. def on_mouse_move(event):
  38.     canvas.delete("highlight")
  39.     xm, ym = get_cell_index(event.x, event.y)
  40.     ncol, nrow = nearest_px2b(xm, ym, cx, cy)
  41.        
  42.     x0 = xm * cell_w
  43.     y0 = ym * cell_h
  44.     x1 = x0 + cell_w
  45.     y1 = y0 + cell_h
  46.     canvas.create_rectangle(x0, y0, x1, y1, fill="orange", tags="highlight")
  47.    
  48.     nx0 = ncol * cell_w
  49.     ny0 = nrow * cell_h
  50.     nx1 = nx0 + cell_w
  51.     ny1 = ny0 + cell_h
  52.     canvas.create_rectangle(nx0, ny0, nx1, ny1, fill="lime", tags="highlight")
  53.    
  54. for i in range(1, grid_cols):
  55.     canvas.create_line(i * cell_w, 0, i * cell_w, canvas_size, fill="gray")
  56. for j in range(1, grid_rows):
  57.     canvas.create_line(0, j * cell_h, canvas_size, j * cell_h, fill="gray")
  58.  
  59. canvas.bind("<Motion>", on_mouse_move)
  60.  
  61. root.mainloop()
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement