2

I use tkinter's canvas to load an image and draw a vector on top of it (using create_line).

I would like to restrict the mouse movement when drawing this vector, so that it cannot be dragged outside of the image area, whatever it may be. The mouse cursor should just snap back to image boundaries.

I tried searching, and found various ways of dealing with this, ideally this would need to be cross-platform. So far, I couldn't make any of those various ways working... so I'm kindly asking for help! Thank you :)

2
  • What are the ways you've found? That might save somebody the trouble of posting a solution that you've already rejected. Commented Jul 16, 2015 at 14:53
  • That would be this: stackoverflow.com/a/16704353/5060127 I cannot seem to find a way to make it work for my canvas, to restrict the mouse cursor movement to its boundaries. :( Commented Jul 16, 2015 at 15:20

1 Answer 1

2

OK in the end I decided not to restrict mouse cursor physically (by forcing it not to go beyond certain coordinates), but rather virtually (by storing the mouse position to a variable, then if-elseing it around the bounding box that it needed to stay in). So the mouse cursor goes wherever it wants, but when it's actually drawing something in - it stays within the designated area I want it to.

Drawing lines on a Canvas was the task, over the loaded image. Line shouldn't pass by the boundaries of the image. This is how it worked out:

imgsize = (int(self.viewport.cget('width')) - 1,int(self.viewport.cget('height')) - 1)
# limit the draggable mouse area to just the image dimensions
if event.x < 4:
    currentx = 4
elif event.x > imgsize[0]:
    currentx = imgsize[0]
else:
    currentx = event.x
if event.y < 4:
    currenty = 4
elif event.y > imgsize[1]:
    currenty = imgsize[1]
else:
    currenty = event.y

Then from that point onward it's create_line time.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.