Daniel Huckson
Daniel Huckson

Reputation: 1247

Treeview how to select multiple rows using cursor up and down keys

I've been trying to figure out what I need to do to select multiple rows in the treeview widget using the keyboard. I have tried all the different bindings and I can't seem to get anything to work correctly. It seems my calls have no effect.

I have provied the code I'm using to test this I must be missing something!

from tkinter import *
from tkinter.ttk import Treeview


class App(Frame):

    def __init__(self, parent):
        super().__init__()
        self.container = Frame.__init__(self, parent)

        self.tv = None
        self.tree()

        def shift_down(event):
            _widget = event.widget
            _focus = event.widget.focus()
            _widget.selection_add(_focus)
            print(_focus)

        self.tv.bind('<Shift-Down>', lambda e: shift_down(e))

    def tree(self):
        tv = self.tv = Treeview(self.container)
        tv.grid(sticky='NSEW')

        tv.insert('', '0', 'item1', text='Item 1', tags='row')
        tv.insert('', '1', 'item2', text='Item 2', tags='row')
        tv.insert('', '2', 'item3', text='Item 3', tags='row')

        tv.insert('item1', '0', 'python1', text='Python 1')
        tv.insert('item1', '1', 'python2', text='Python 2')

        tv.insert('python1', '0', 'sub1', text='Sub item 1')
        tv.insert('python1', '1', 'sub2', text='Sub item 2')


def main():
    root = Tk()

    root.grid_rowconfigure(0, weight=1)
    root.grid_columnconfigure(0, weight=1)
    App(root)

    root.mainloop()


if __name__ == '__main__':
    main()

Upvotes: 1

Views: 996

Answers (1)

stovfl
stovfl

Reputation: 15533

Question: select multiple rows using cursor up and down keys


"I have tried all the different bindings and I can't seem to get anything to work correctly. It seems my calls have no effect."

You want to change standard behavior of a ttk.Treeview. Since your above binding applies to the instance level only, and the standard behavior is provided by a class level bindings. Therefore all your changes are reverted, thats why you see no effect.

To prevent Tkinter from propagating the event to other handlers; just return the string “break” from your event handler:



For example:
Note: Here, only <Shift-Down> is shown.

There is no need to use lambda:.

self.tv.bind('<Shift-Down>', shift_down)

def shift_down(event):
    tree = event.widget
    cur_item = tree.focus()

    # You need the next item, because you `"break"` standard behavior
    next_item = tree.next(cur_item)

    # Set the keyboard focus to the `next_item`
    tree.focus(next_item)

    # Add both items to the `selection` list
    tree.selection_add([cur_item, next_item])

    print('shift_down cur_item:{}\nselection:{}'\
        .format(cur_item, tree.selection()))

    # Stop propagating this event to other handlers!
    return 'break'

Tested with Python: 3.5

Upvotes: 2

Related Questions