在Tkinter UI中拖放对象

2024-09-29 05:21:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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()

在这里,我观察到,当我开始拖动对象时,这张卡和另一张卡正好向下移动。我怎样才能解决它


Tags: eventbindtkinteranotherplacerootcardwindow
2条回答

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

我得出了以下结论,但并不比TheLizzard的答案好多少

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()

试试这个:

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位置

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

相关问题 更多 >