您正在观察的行为是由事件的坐标相对于拖动的窗口部件引起的。更新小部件的位置(在绝对坐标)与相对坐标显然导致混乱。
为了解决这个问题,我使用了.winfo_x()
and .winfo_y()
函数(允许将相对坐标转换为绝对坐标)和Button-1
事件来确定拖动开始时光标在控件上的位置。 以下是一个混合使得一个小部件可拖动。
class DragDropWidget:
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.drag_start_x = 0
self.drag_start_y = 0
self.bind("<Button-1>", self.drag_start)
self.bind("<B1-Motion>", self.drag_motion)
def drag_start(self, event):
self.drag_start_x = event.x
self.drag_start_y = event.y
def drag_motion(self, event):
x = self.winfo_x() - self.drag_start_x + event.x
y = self.winfo_y() - self.drag_start_y + event.y
self.place(x=x, y=y)
用法:
# As always when it comes to mixins, make sure to
# inherit from DragDropWidget FIRST!
class DnDFrame(DragDropWidget, tk.Frame):
pass
# This wouldn't work:
# class DnDFrame(tk.Frame, DragDropWidget):
# pass
main = tk.Tk()
notesFrame = DnDFrame(main, bd = 4, bg = "grey")
notesFrame.place(x=10,y=10)
notes = tk.Text(notesFrame)
notes.pack()
你真的尝试* *这个代码?因为它有多个错误,并且不会移动任何东西 - 至少在Mac上的Python 3.5下。 –
你有点击边框,而不是文本框 –