Reputation: 69
I'm developing a way to position widgets at runtime using tkinter's place() method, to make it easier to configure a form with entries, for example.
I made a test code and it doesn't work very well. Stick with a skipping widget in the window.
The code is this:
import tkinter as tk
from tkinter import ttk
list_pos = [[20, 20]]
def move(event):
list_pos[0][0] = event.x + 10
list_pos[0][1] = event.y + 10
#print(list_pos[0][0], list_pos[0][1])
b1.place(x=list_pos[0][0], y=list_pos[0][1])
root = tk.Tk()
b1 = ttk.Button(root, text="OK")
b1.place(x=list_pos[0][0], y=list_pos[0][1])
b1.bind('<B1-Motion>', move)
root.mainloop()
Upvotes: 1
Views: 135
Reputation: 39818
Event coordinates are relative to the widget on which the event is reported, but widget coordinates are relative to the parent widget, so it is wrong to use one to set the other (with or without a constant offset like the + 10
here). Instead, convert one to the other:
def move(event):
w=event.widget
w.place(x=event.x+w.winfo_x(), y=event.y+w.winfo_y())
Then add whatever desired offset, perhaps from the click location to get a smooth start.
Upvotes: 2