Python使用tkinter.dnd实现控件拖拽功能
时间: 2024-09-12 07:15:52 浏览: 73
Python-Tkinter.rar
在Python中,Tkinter模块的`dnd`(Dropping and Dragging)模块提供了一组类和方法,用于实现基于鼠标点击和拖动的控件之间的数据传输。以下是一个基本的使用示例,展示如何创建一个简单的Tkinter窗口,其中包含一个可拖动的Label组件,并能在指定的目标位置放下:
```python
import tkinter as tk
from tkinter import dnd
class DraggableLabel(tk.Label):
def __init__(self, parent, text, **kwargs):
super().__init__(parent, text=text, **kwargs)
self.bind("<ButtonPress-1>", self.start_dragging)
self.tagbind("all", "<B1-Motion>", self.update_position)
self.tagbind("all", "<ButtonRelease-1>", self.stop_dragging)
def start_dragging(self, event):
self.x orig, self.y orig = event.x, event.y
self.tk.eval("dnd::start {} {}".format(self.winfo_id(), self["command"]))
def update_position(self, event):
x, y = event.x, event.y
dx, dy = x - self.x orig, y - self.y orig
self.geometry("+{}+{}".format(dx, dy))
self.x orig, self.y orig = x, y
def stop_dragging(self, event=None):
self.tk.eval("dnd::stop")
root = tk.Tk()
drag_label = DraggableLabel(root, "Drag Me!")
drag_label.pack()
# 设置一个接收标签的地方作为目标
target_frame = tk.Frame(root)
target_frame.pack(fill="both", expand=True)
target_frame.bind("<Motion>", lambda e: target_frame.configure(cursor="hand2"))
# 当标签到达目标时,执行特定命令
def drop_function():
print("Label dropped at:", drag_label.winfo_pos())
drag_label.bind("<<Drop>>", drop_function)
root.mainloop()
阅读全文