changing order of items in tkinter listbox

2019-01-26 00:42发布

问题:

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?

For example, I want to be able to re-arrange items in a listbox. If I want to swap the position of two, this is what I've done. It works, but I just want to see if there's a quicker way to do this.

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)

回答1:

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?

No. Deleting and re-inserting is the only way. If you just want to move a single item up by one you can do it with only one delete and insert, though.

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)


回答2:

To expand on Tim's answer, it is possible to do this for multiple items as well if you use the "currentselection()" function of the tkinter.listbox.

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)

This would move all selected items up 1 position. It could also be easily adapted to move the items down. You would have to check if the item was at the end of the list instead of the top, and then add 1 to the index instead of subtract. You would also want to reverse the list for the loop so that the changing indexes wouldn't mess up future moves in the set.