在 Tkinter UI 中拖放对象 [英] Drag and drop the object in Tkinter UI

查看:29
本文介绍了在 Tkinter UI 中拖放对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on making an HPE annotation tool using tkinter, and making a drag/drop UI.

我对 tkinter 很陌生,所以我稍微修改了其他 stackoverflow 问题中的代码,如下所示.

I am very new to tkinter so I slightly modified the code in other stackoverflow issue and it is as following.

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

在这里,当我开始拖动对象时,我观察到卡片和另一张卡片向右下方移动.我该如何解决?

Here I observed that the card and another card goes down-right when I started to drag the objects. How can I solve it ?

推荐答案

试试这个:

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.x gives the x position of the cursor according to the widget.

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

event.widget.winfo_x() gives the x position of the widget according to the window.

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

By the way it would have been much simpler if you moved both of the widgets inside a canvas but it still works.

这篇关于在 Tkinter UI 中拖放对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆