【发布时间】:2021-06-09 10:05:18
【问题描述】:
我正在尝试使用拖放在 tkinter 的网格布局中交换两个小部件的位置。在鼠标 ButtonRelease-1 上,我想获取释放鼠标的小部件 (myTextLabel2),以便我可以使用单击的小部件 (myTextLabel1) 的行和列更改该小部件的行和列。
我尝试搜索在位置 x,y 处获取小部件的方法,但我只能找到相反的方法,获取小部件的位置而不是相反。
到目前为止,这是我的代码:
from tkinter import *
from functools import partial
def changeOrder(widget1,widget2):
widget1.grid(row=1,column=0)
widget2.grid(row=0,column=0)
def drag_start(event):
print(event.x)
def drag_motion(event):
x = event.x
y = event.y
def drag_release(event):
x = event.x
y = event.y
#I want to get the widget at position x,y, should be myTextLabel2
#Then swap the rows and columns for myTextLabel2 and myTextLabel1
root = Tk()
myTextLabel1 = Label(root,text="Label 1")
myTextLabel1.grid(row=0,column=0,padx=5,pady=5,sticky=E+W+S+N)
myTextLabel1.bind("<Button-1>",drag_start)
myTextLabel1.bind("<B1-Motion>",drag_motion)
myTextLabel1.bind("<ButtonRelease-1>",drag_release)
myTextLabel2 = Label(root,text="Label 2")
myTextLabel2.grid(row=1,column=0,padx=5,pady=5,sticky=E+W+S+N)
myButton = Button(root,text="Change order",command=partial(changeOrder,myTextLabel1,myTextLabel2))
myButton.grid(row=3,column=0,padx=5,pady=5,sticky=E+W+S+N)
root.mainloop()
【问题讨论】: