Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

Tkinter canvas draggable

def make_draggable(widget, btn="<Button-1>", motion="<B1-Motion>"):
    def __draggable__(widget):
        c.tag_bind(widget, btn, on_drag_start)
        c.tag_bind(widget, motion, on_drag_motion)
        c._item_id = widget # save the item ID for later use

    def on_drag_start(event):
        widget = event.widget
        # get the top-left coordinates of the selected item
        x, y, *_ = widget.bbox(widget._item_id)
        # save the offset of current mouse position from the top-left coordinates
        widget._dx = event.x - x
        widget._dy = event.y - y

    def on_drag_motion(event):
        widget = event.widget
        # calculate the top-left coordinates of the item that the item to be moved to
        x = event.x - widget._dx
        y = event.y - widget._dy
        # move the item using moveto() instead of move()
        widget.moveto(widget._item_id, x, y)

    __draggable__(widget)
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #Tkinter #canvas #draggable
ADD COMMENT
Topic
Name
5+2 =