Home > Blockchain >  How to make a square follow mouse cursor inside grid
How to make a square follow mouse cursor inside grid

Time:01-23

I'm trying to make a square follow mouse cursor inside Tkinter grid.

I'm using this code to create a grid:

for gr in range(0, 400, 10):
    canvas.create_line(0,gr, 400,gr, fill='#cfcfcf', width=1)
for gr in range(0,400, 10):
    canvas.create_line(gr,0, gr,400, fill='#cfcfcf', width=1)

I bind canvas to cursor "Motion":

def cursor_move(event):
    x, y= event.x, event.y
    cursor = canvas.find_withtag('cursor') #cursor is my square which I want to move
    canvas.moveto(cursor, newx, newy)

But I have no idea how to get newx and newy values.
Thanks for your help!

CodePudding user response:

If you want the square snapping at the grid, try:

def cursor_move(event):
    # calculate grid x and y based on mouse x and y
    x, y = event.x//10*10, event.y//10*10
    canvas.moveto('cursor', x-1, y-1)
  •  Tags:  
  • Related