我正在使用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()
在这里,我观察到,当我开始拖动对象时,这张卡和另一张卡正好向下移动。我怎样才能解决它
为了补充说明,您是否注意到您的拖动量等于窗口在屏幕上的位置?如果窗口最大化,那么代码就非常接近了。如果缩小窗口的大小并从左上角移得更远,则三角洲会变得更糟。这是因为
event.x_root
和event.y_root
是绝对坐标,从屏幕左上角开始,但是place
的参数是相对于窗口左上角的。你总是需要意识到你的坐标是相对于什么的我得出了以下结论,但并不比TheLizzard的答案好多少
试试这个:
event.x
根据小部件给出光标的x位置event.widget.winfo_x()
根据窗口给出小部件的x位置顺便说一句,如果将这两个小部件都移动到画布中,会简单得多,但它仍然可以工作
相关问题 更多 >
编程相关推荐