listbox拖动排序,
时间: 2023-10-24 20:10:11 浏览: 103
好的,针对你的问题,我可以给出以下思路:
1. 获取listbox中被拖动的项的索引
2. 获取鼠标当前位置所在的项的索引
3. 将被拖动的项从listbox中删除
4. 将被拖动的项插入到当前位置所在的项之前或之后
具体实现可以参考以下代码:
```python
import tkinter as tk
class DragDropListbox(tk.Listbox):
"""可拖动排序的Listbox"""
def __init__(self, master, **kw):
kw['selectmode'] = tk.SINGLE
kw['activestyle'] = 'none'
super().__init__(master, kw)
self.bind('<Button-1>', self.on_select)
self.bind('<B1-Motion>', self.on_drag)
self.bind('<Leave>', self.on_leave)
def on_select(self, event):
"""选中项"""
self._dragged_index = self.nearest(event.y)
def on_drag(self, event):
"""拖动项"""
current_index = self.nearest(event.y)
if current_index != self._dragged_index:
text = self.get(self._dragged_index)
self.delete(self._dragged_index)
if current_index > self._dragged_index:
current_index -= 1
self.insert(current_index, text)
self._dragged_index = current_index
def on_leave(self, event):
"""离开Listbox时清除选中项"""
self._dragged_index = None
# 测试代码
if __name__ == '__main__':
root = tk.Tk()
root.geometry('200x200')
lb = DragDropListbox(root)
for i in range(10):
lb.insert(tk.END, f'Item {i}')
lb.pack(expand=True, fill=tk.BOTH)
root.mainloop()
```
阅读全文