Mario Krušelj
Mario Krušelj

Reputation: 703

Python tkinter: how to restrict mouse cursor within canvas?

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 :)

Upvotes: 2

Views: 1586

Answers (1)

Mario Krušelj
Mario Krušelj

Reputation: 703

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.

Upvotes: 2

Related Questions