更改tkinter列表框中项目的顺序

2024-10-02 18:21:34 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有比删除特定键的值然后重新输入新信息更容易更改tkinter列表框中项目的顺序的方法?在

例如,我希望能够重新排列列表框中的项目。如果我想交换两个人的位置,这就是我所做的。它很管用,但我只想看看有没有更快的方法。在

def moveup(self,selection):
    value1 = int(selection[0]) - 1 #value to be moved down one position
    value2 = selection #value to be moved up one position
    nameAbove = self.fileListSorted.get(value1) #name to be moved down
    nameBelow = self.fileListSorted.get(value2) #name to be moved up

    self.fileListSorted.delete(value1,value1)
    self.fileListSorted.insert(value1,nameBelow)
    self.fileListSorted.delete(value2,value2)
    self.fileListSorted.insert(value2,nameAbove)

Tags: to项目方法selfvaluepositionbeone
2条回答

Is there an easier way to change the order of items in a tkinter listbox than deleting the values for specific key, then re-entering new info?

不可以。删除和重新插入是唯一的方法。如果您只想将一个项目上移一个,那么只需一次删除和插入即可。在

def move_up(self, pos):
    """ Moves the item at position pos up by one """

    if pos == 0:
        return

    text = self.fileListSorted.get(pos)
    self.fileListSorted.delete(pos)
    self.fileListSorted.insert(pos-1, text)

为了扩展Tim的答案,如果使用tkinter.listboxcurrentselection()函数,也可以对多个项目执行此操作。在

l = self.lstListBox
posList = l.curselection()

# exit if the list is empty
if not posList:
    return

for pos in posList:

    # skip if item is at the top
    if pos == 0:
        continue

    text = l.get(pos)
    l.delete(pos)
    l.insert(pos-1, text)

这将把所有选中的项目上移1位置。它也可以很容易地适应移动项目向下。您必须检查该项是否位于列表的末尾而不是顶部,然后将1添加到索引中,而不是减去。您还需要反转循环的列表,这样不断变化的索引就不会扰乱集合中未来的移动。在

相关问题 更多 >