here2share

# Tk_snap2grid.py

Nov 7th, 2019 (edited)
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.95 KB | None | 0 0
  1. # Tk_snap2grid.py
  2.  
  3. import tkinter as tk
  4.  
  5. def Snap2Grid(width=300, height=300):
  6.     canvas.config(width=width, height=height)
  7.     for x in range(1,width,50):
  8.         canvas.create_line(x,0, x,height)
  9.     for y in range(1,height,50):
  10.         canvas.create_line(0,y, width,y)
  11.     canvas.create_rectangle(51,51, 101,101, fill="red",
  12.                           activefill='green', tag="R")
  13. 0
  14. root = tk.Tk()
  15. canvas = tk.Canvas()
  16. canvas.pack()
  17. canvas.click = None
  18.  
  19. def onClick1(event):
  20.     canvas.click = event.x, event.y
  21.     canvas.delete('cpoint')
  22. def onMotion1(event):
  23.     x, y = canvas.click
  24.     dx = event.x - x
  25.     dy = event.y - y
  26.     canvas.move('current' ,dx ,dy)
  27.     canvas.click = event.x, event.y
  28. def onRelease1(event):
  29.     mx, my = event.x, event.y
  30.     x, y = mx-(mx%50)+1, my-(my%50)+1
  31.     canvas.coords("R", x,y, x+50,y+50)
  32. canvas.tag_bind("R", "<Button-1>", onClick1)
  33. canvas.tag_bind("R", "<B1-Motion>", onMotion1)
  34. canvas.tag_bind("R", "<ButtonRelease-1>",onRelease1)
  35.  
  36. Snap2Grid()
  37. root.mainloop()
Add Comment
Please, Sign In to add comment