<p>Tkinter不直接支持在应用程序中拖放。但是,拖放只需要为按钮单击(<code><ButtonPress-1></code>)、单击按钮时移动鼠标(<code><B1-Motion></code>)和释放按钮时移动鼠标(<code><ButtonRelease-1></code>)创建合适的绑定。</p>
<p>下面是一个非常简单的示例,它是为处理您的代码而设计的。</p>
<p>首先,我们将创建一个可以管理拖放的类。作为一个类而不是全局函数的集合这样做更容易。</p>
<pre><code>class DragManager():
def add_dragable(self, widget):
widget.bind("<ButtonPress-1>", self.on_start)
widget.bind("<B1-Motion>", self.on_drag)
widget.bind("<ButtonRelease-1>", self.on_drop)
widget.configure(cursor="hand1")
def on_start(self, event):
# you could use this method to create a floating window
# that represents what is being dragged.
pass
def on_drag(self, event):
# you could use this method to move a floating window that
# represents what you're dragging
pass
def on_drop(self, event):
# find the widget under the cursor
x,y = event.widget.winfo_pointerxy()
target = event.widget.winfo_containing(x,y)
try:
target.configure(image=event.widget.cget("image"))
except:
pass
</code></pre>
<p>要使用它,您只需要调用<code>add_draggable</code>方法,为它提供希望拖动的小部件。</p>
<p>例如:</p>
<pre><code>label = Label(canvas, image=image)
...
dnd = DragManager()
dnd.add_dragable(label)
...
root.mainloop()
</code></pre>
<p>这就是基本框架所需要的一切。这取决于您创建一个浮动的可拖动窗口,并可能突出显示可以放置的项。</p>
<h2>其他实现</h2>
<p>有关同一概念的另一个实现,请参见<a href="https://github.com/python/cpython/blob/master/Lib/tkinter/dnd.py" rel="noreferrer">https://github.com/python/cpython/blob/master/Lib/tkinter/dnd.py</a></p>