Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tkinter: dragging widgets

I'd like to make a drag-n-drop function for a widget. The code is this:

from tkinter import *


root = Tk()
root.config(background = "red", width = 500, height = 500)
root.title("root")

def frameDrag(event):
    frame.place(x = event.x , y = event.y)

frame = Frame(root, width = 60, height = 30)
frame.place(x=0, y=0)
frame.bind("<B1-Motion>", frameDrag)

root.mainloop()

Basically, it should place the widget to the location you move your mouse to. Instead, the widget jumps around all over the window. Any ideas how to fix this?

like image 825
drakide Avatar asked Apr 10 '26 07:04

drakide


1 Answers

It is jumping all over the place because you are telling it to as shown by:

def frameDrag(event):
    print event.x, event.y
    frame.place(x = event.x , y = event.y)

Better to use a canvas widget and better to use B1-Click and B1-Release events and compute the delta. Look for the widget demo that comes along with Tkinter.

like image 92
msw Avatar answered Apr 11 '26 21:04

msw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!