Tkinter: drag and drop widgets

I want to make a drag-n-drop function for a widget. The code looks like 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 in the place where you move the mouse. Instead, the widget moves around the window. Any ideas how to fix this?

+3
source share
1 answer

He jumps everywhere because you tell him, as shown in the figure:

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

It’s better to use the canvas widget and it’s better to use the B1-Click and B1-Release events and calculate the delta. Look for the demo version of the widget that comes with Tkinter.

+1
source

Source: https://habr.com/ru/post/1755105/


All Articles