Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # nearest_px2b.py
- import tkinter as tk
- import math
- grid_rows, grid_cols = 9, 9
- canvas_size = 600
- cell_w = canvas_size / grid_cols
- cell_h = canvas_size / grid_rows
- cx, cy = grid_rows // 2, grid_cols // 2
- root = tk.Tk()
- root.title("# nearest_px2b.py")
- root.geometry(f"+10+10")
- canvas = tk.Canvas(root, width=canvas_size, height=canvas_size, bg='white')
- canvas.pack()
- def nearest_px2b(x, y, x0, y0):
- dx = x0 - x
- dy = y0 - y
- print(x, y, x0, y0)
- length = math.sqrt(dx*dx + dy*dy)
- if length == 0:
- return (x, y)
- step_x = int(round(dx / length))
- step_y = int(round(dy / length))
- neighbor = (x + step_x, y + step_y)
- return neighbor
- def get_cell_index(x, y):
- col = int(x // cell_w)
- row = int(y // cell_h)
- col = min(grid_cols-1, col)
- row = min(grid_rows-1, row)
- return (col, row)
- def on_mouse_move(event):
- canvas.delete("highlight")
- xm, ym = get_cell_index(event.x, event.y)
- ncol, nrow = nearest_px2b(xm, ym, cx, cy)
- x0 = xm * cell_w
- y0 = ym * cell_h
- x1 = x0 + cell_w
- y1 = y0 + cell_h
- canvas.create_rectangle(x0, y0, x1, y1, fill="orange", tags="highlight")
- nx0 = ncol * cell_w
- ny0 = nrow * cell_h
- nx1 = nx0 + cell_w
- ny1 = ny0 + cell_h
- canvas.create_rectangle(nx0, ny0, nx1, ny1, fill="lime", tags="highlight")
- for i in range(1, grid_cols):
- canvas.create_line(i * cell_w, 0, i * cell_w, canvas_size, fill="gray")
- for j in range(1, grid_rows):
- canvas.create_line(0, j * cell_h, canvas_size, j * cell_h, fill="gray")
- canvas.bind("<Motion>", on_mouse_move)
- root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement