Python中使用tkinter实现列表框的拖放功能

5

有人能告诉我如何制作一个具有拖放功能的列表框以便重新排列吗?我已经找到了一些关于Perl的相关信息,但我对这种语言一无所知,而且我对tkinter也比较陌生,因此很困惑。我知道如何生成列表框,但我不知道如何通过拖放来重新排序。

3个回答

8

以下是11.4 节的代码:

import Tkinter 

class DragDropListbox(Tkinter.Listbox):
    """ A Tkinter listbox with drag'n'drop reordering of entries. """
    def __init__(self, master, **kw):
        kw['selectmode'] = Tkinter.SINGLE
        Tkinter.Listbox.__init__(self, master, kw)
        self.bind('<Button-1>', self.setCurrent)
        self.bind('<B1-Motion>', self.shiftSelection)
        self.curIndex = None

    def setCurrent(self, event):
        self.curIndex = self.nearest(event.y)

    def shiftSelection(self, event):
        i = self.nearest(event.y)
        if i < self.curIndex:
            x = self.get(i)
            self.delete(i)
            self.insert(i+1, x)
            self.curIndex = i
        elif i > self.curIndex:
            x = self.get(i)
            self.delete(i)
            self.insert(i-1, x)
            self.curIndex = i

4

如果您的 selectmodeMULTIPLE 而不是 SINGLE,以下是修改后的代码:

更改内容如下:

  1. 当拖动已选择的项目时,它会取消选择,这会给用户带来不好的体验。
  2. 当单击一个已选择的项目时,它会从单击中取消选择。因此,我添加了一个 self.curState 位来跟踪被单击项目的状态是否最初被选择。当您将其拖动时,它不会失去其状态。
  3. 我还使用 add='+' 将两个事件绑定到 Button-1 事件,但这可能可以通过全部保留在 setCurrent 下来避免。
  4. 我更喜欢 activestyle 等于 'none'
  5. 将此 Listbox 设置为 tk.MULTIPLE 而不是 tk.SINGLE

以下是代码:

class Drag_and_Drop_Listbox(tk.Listbox):
  """ A tk listbox with drag'n'drop reordering of entries. """
  def __init__(self, master, **kw):
    kw['selectmode'] = tk.MULTIPLE
    kw['activestyle'] = 'none'
    tk.Listbox.__init__(self, master, kw)
    self.bind('<Button-1>', self.getState, add='+')
    self.bind('<Button-1>', self.setCurrent, add='+')
    self.bind('<B1-Motion>', self.shiftSelection)
    self.curIndex = None
    self.curState = None
  def setCurrent(self, event):
    ''' gets the current index of the clicked item in the listbox '''
    self.curIndex = self.nearest(event.y)
  def getState(self, event):
    ''' checks if the clicked item in listbox is selected '''
    i = self.nearest(event.y)
    self.curState = self.selection_includes(i)
  def shiftSelection(self, event):
    ''' shifts item up or down in listbox '''
    i = self.nearest(event.y)
    if self.curState == 1:
      self.selection_set(self.curIndex)
    else:
      self.selection_clear(self.curIndex)
    if i < self.curIndex:
      # Moves up
      x = self.get(i)
      selected = self.selection_includes(i)
      self.delete(i)
      self.insert(i+1, x)
      if selected:
        self.selection_set(i+1)
      self.curIndex = i
    elif i > self.curIndex:
      # Moves down
      x = self.get(i)
      selected = self.selection_includes(i)
      self.delete(i)
      self.insert(i-1, x)
      if selected:
        self.selection_set(i-1)
      self.curIndex = i

示例演示:

root = tk.Tk()
listbox = Drag_and_Drop_Listbox(root)
for i,name in enumerate(['name'+str(i) for i in range(10)]):
  listbox.insert(tk.END, name)
  if i % 2 == 0:
    listbox.selection_set(i)
listbox.pack(fill=tk.BOTH, expand=True)
root.mainloop()

我稍微尝试了一下,发现它只允许一次移动一个项目,无论选择了多少个项目。用户希望所有选定的项目一起移动,因此我建议在解决这个问题之前仅在“SINGLE”模式下使用它。我还更改了getState()方法中的最后一行为self.curState = 1,这样当未选择的行移动时,它只是保持选定状态,而不是奇怪地闪烁选定状态。这在“SINGLE”模式下看起来非常好,因为它突出显示了用户正在移动/最后移动的内容。 - TheAtomicOption

1
以下是一个带有“扩展”选择模式的Listbox类,使得可以拖动多个选定项目。
  • 默认选择机制被保留(通过拖动和单击,包括按住Ctrl或Shift),但如果不按住Ctrl拖动已选择的项目,则除外。
  • 要拖动选择,请将所选项目之一拖到最后所选项目下方或第一个所选项目上方。
  • 在拖动选择时滚动列表框,请使用鼠标滚轮或将光标移动到列表框的顶部或底部附近或超出列表框。=> 这可以改进:因为它绑定到B1-Motion事件,需要额外移动鼠标才能继续滚动。在较长的列表框中感觉有点错误。
  • 如果选择是不连续的,则拖动将通过向上或向下移动未选定的项目使其连续。
以上意味着要拖动一个项目,需要先选择它,然后再次单击并拖动。
import tkinter as tk;

class ReorderableListbox(tk.Listbox):
    """ A Tkinter listbox with drag & drop reordering of lines """
    def __init__(self, master, **kw):
        kw['selectmode'] = tk.EXTENDED
        tk.Listbox.__init__(self, master, kw)
        self.bind('<Button-1>', self.setCurrent)
        self.bind('<Control-1>', self.toggleSelection)
        self.bind('<B1-Motion>', self.shiftSelection)
        self.bind('<Leave>',  self.onLeave)
        self.bind('<Enter>',  self.onEnter)
        self.selectionClicked = False
        self.left = False
        self.unlockShifting()
        self.ctrlClicked = False
    def orderChangedEventHandler(self):
        pass

    def onLeave(self, event):
        # prevents changing selection when dragging
        # already selected items beyond the edge of the listbox
        if self.selectionClicked:
            self.left = True
            return 'break'
    def onEnter(self, event):
        #TODO
        self.left = False

    def setCurrent(self, event):
        self.ctrlClicked = False
        i = self.nearest(event.y)
        self.selectionClicked = self.selection_includes(i)
        if (self.selectionClicked):
            return 'break'

    def toggleSelection(self, event):
        self.ctrlClicked = True

    def moveElement(self, source, target):
        if not self.ctrlClicked:
            element = self.get(source)
            self.delete(source)
            self.insert(target, element)

    def unlockShifting(self):
        self.shifting = False
    def lockShifting(self):
        # prevent moving processes from disturbing each other
        # and prevent scrolling too fast
        # when dragged to the top/bottom of visible area
        self.shifting = True

    def shiftSelection(self, event):
        if self.ctrlClicked:
            return
        selection = self.curselection()
        if not self.selectionClicked or len(selection) == 0:
            return

        selectionRange = range(min(selection), max(selection))
        currentIndex = self.nearest(event.y)

        if self.shifting:
            return 'break'

        lineHeight = 15
        bottomY = self.winfo_height()
        if event.y >= bottomY - lineHeight:
            self.lockShifting()
            self.see(self.nearest(bottomY - lineHeight) + 1)
            self.master.after(500, self.unlockShifting)
        if event.y <= lineHeight:
            self.lockShifting()
            self.see(self.nearest(lineHeight) - 1)
            self.master.after(500, self.unlockShifting)

        if currentIndex < min(selection):
            self.lockShifting()
            notInSelectionIndex = 0
            for i in selectionRange[::-1]:
                if not self.selection_includes(i):
                    self.moveElement(i, max(selection)-notInSelectionIndex)
                    notInSelectionIndex += 1
            currentIndex = min(selection)-1
            self.moveElement(currentIndex, currentIndex + len(selection))
            self.orderChangedEventHandler()
        elif currentIndex > max(selection):
            self.lockShifting()
            notInSelectionIndex = 0
            for i in selectionRange:
                if not self.selection_includes(i):
                    self.moveElement(i, min(selection)+notInSelectionIndex)
                    notInSelectionIndex += 1
            currentIndex = max(selection)+1
            self.moveElement(currentIndex, currentIndex - len(selection))
            self.orderChangedEventHandler()
        self.unlockShifting()
        return 'break'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接