在Tkinter UI中拖放对象



我正在使用tkinter制作一个HPE注释工具,并制作一个拖放UI。

我是tkinter的新手,所以我在其他stackoverflow问题中稍微修改了代码,如下所示。

from tkinter import *
window = Tk()
window.state('zoomed')
window.configure(bg = 'white')
def drag(event):
event.widget.place(x=event.x_root, y=event.y_root,anchor=CENTER)
card = Canvas(window, width=10, height=10, bg='blue2')
card.place(x=300, y=600,anchor=CENTER)
card.bind("<B1-Motion>", drag)
another_card = Canvas(window, width=10, height=10, bg='red3')
another_card.place(x=600, y=600,anchor=CENTER)
another_card.bind("<B1-Motion>", drag)
window.mainloop()

在这里,我观察到当我开始拖动对象时,这张卡和另一张卡正好向下。我该如何解决?

试试这个:

from tkinter import *
window = Tk()
# window.state("zoomed")
window.configure(bg="white")
def drag(event):
x = event.x + event.widget.winfo_x()
y = event.y + event.widget.winfo_y()
event.widget.place(x=x, y=y, anchor="center")
card = Canvas(window, width=10, height=10, bg="blue")
card.place(x=50, y=50, anchor="center")
card.bind("<B1-Motion>", drag)
another_card = Canvas(window, width=10, height=10, bg="red")
another_card.place(x=100, y=50, anchor="center")
another_card.bind("<B1-Motion>", drag)
window.mainloop()

event.x根据小部件给出光标的x位置。

event.widget.winfo_x()根据窗口给出小部件的x位置。

顺便说一句,如果您将两个小部件都移动到画布内,它会简单得多,但它仍然可以工作。

只是添加一个解释,您是否注意到您的拖动量等于窗口在屏幕上的位置?如果窗口被最大化,那么您的代码就非常接近了。如果缩小窗口的大小并从左上角移动得更远,则delta会变得更糟。这是因为event.x_rootevent.y_root是从屏幕左上角开始的绝对坐标,但place的参数相对于窗口的左上角。你总是需要意识到你的坐标是相对于什么的。

我想出了以下的办法,但这并不比丽佐的回答好多少。

from tkinter import *
window = Tk()
window.state('zoomed')
window.configure(bg = 'white')
def drag(event):
new_x = event.x_root - window.winfo_rootx()
new_y = event.y_root - window.winfo_rooty()
event.widget.place(x=new_x, y=new_y,anchor=CENTER)
card = Canvas(window, width=10, height=10, bg='blue2')
card.place(x=300, y=600,anchor=CENTER)
card.bind("<B1-Motion>", drag)
another_card = Canvas(window, width=10, height=10, bg='red3')
another_card.place(x=600, y=600,anchor=CENTER)
another_card.bind("<B1-Motion>", drag)
window.mainloop()

最新更新