Python tkinter: how to restrict mouse cursor within canvas? -


i use tkinter's canvas load image , draw vector on top of (using create_line).

i restrict mouse movement when drawing vector, cannot dragged outside of image area, whatever may be. mouse cursor should snap image boundaries.

i tried searching, , found various ways of dealing this, ideally need cross-platform. far, couldn't make of various ways working... i'm kindly asking help! thank :)

ok in end decided not restrict mouse cursor physically (by forcing not go beyond coordinates), rather virtually (by storing mouse position variable, if-elseing around bounding box needed stay in). mouse cursor goes wherever wants, when it's drawing in - stays within designated area want to.

drawing lines on canvas task, on loaded image. line shouldn't pass boundaries of image. how worked out:

imgsize = (int(self.viewport.cget('width')) - 1,int(self.viewport.cget('height')) - 1) # limit draggable mouse area 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 point onward it's create_line time.


Comments