changing order of items in tkinter listbox

后端 未结 2 1792
礼貌的吻别
礼貌的吻别 2020-12-18 15:36

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

2条回答
  •  情深已故
    2020-12-18 16:15

    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.

提交回复
热议问题