m beshay
m beshay

Reputation: 11

move up and down a treeview

I'm populating a tkinter treeview in python using Os.walk() but after populating it I want to be able to reorder the tree leaves using buttons.

The command for moving up the tree works just fine (I want to be able to move multiple leaves at once)

def moveUp():
    leaves = Tree.selection()
    for i in leaves:
        Tree.move(i, Tree.parent(i), Tree.index(i)-1)

But when I reversed it to go down the tree I get a weird bug

def moveDown():
    leaves = Tree.selection()
    for i in leaves:
        Tree.move(i, Tree.parent(i), Tree.index(i)+1)

I can only move a single leaf down, if I select an odd number of leaves then the lowest one moves down, and if I pick an even number of leaves none of them move.

Upvotes: 1

Views: 4102

Answers (3)

Logesh G
Logesh G

Reputation: 640

A corner case must be handled.

If multiple entries are selected and moved up or down, items within the selection gets moved. To handle this corner case,

def moveUp():
    leaves = Tree.selection()
    # if more than 1 item is selected and the selection hit the top, do nothing
    if len(leaves) > 1 and Tree.index(leaves[0]) == 0:
        return
    for i in leaves:
        Tree.move(i, Tree.parent(i), Tree.index(i)-1)


def moveDown():
    leaves = Tree.selection() 
    # if more than 1 item is selected and the selection hit the bottom, do nothing
    if len(leaves) > 1 and Tree.index(leaves[-1]) == len(Tree.get_children())-1:
        return
    for i in reversed(leaves):
        Tree.move(i, Tree.parent(i), Tree.index(i)+1)

Upvotes: 0

ph1nk
ph1nk

Reputation: 1

Note, for moveUp, reversing the leaves would result in nothing actually changing in the tree. Simply iterating through the leaves in order is the ticket.

def moveUp():
    leaves = Tree.selection()
    for i in leaves:
        Tree.move(i, Tree.parent(i), Tree.index(i)-1)

Upvotes: 0

Jack Love
Jack Love

Reputation: 51

As suggested in the comments going through leaves in the reverse order using reversed() fixes the problem. (Would be a comment but I don't have the reputation)

def moveDown():
    leaves = Tree.selection()
    for i in reversed(leaves):
        Tree.move(i, Tree.parent(i), Tree.index(i)+1)

Upvotes: 5

Related Questions