【问题标题】:Treeview how to select multiple rows using cursor up and down keysTreeview如何使用光标上下键选择多行
【发布时间】:2019-09-14 23:09:42
【问题描述】:

我一直试图弄清楚我需要做什么才能使用键盘在树视图小部件中选择多行。我已经尝试了所有不同的绑定,但我似乎无法让任何东西正常工作。 看来我的电话没有任何效果。

我已经提供了我用来测试的代码,我一定是遗漏了什么!

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()

【问题讨论】:

标签: python tkinter treeview


【解决方案1】:

问题:使用上下光标键选择多行


“我已经尝试了所有不同的绑定,但我似乎无法让任何东西正常工作。看来我的调用没有效果。”

您想更改ttk.Treeview 的标准行为。 由于您的上述绑定仅适用于实例级别, 标准行为由类级别绑定提供。 因此,您的所有更改都将被还原,这就是您看到没有效果的原因。

防止Tkinter 将事件传播给其他处理程序;只需从您的事件处理程序中返回字符串 “break”



例如:
注意:这里只显示&lt;Shift-Down&gt;

没有必要使用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'

用 Python 测试:3.5

【讨论】:

  • 这正是我所需要的,非常感谢。我真的在这方面苦苦挣扎,你刚刚启发了我。
猜你喜欢
  • 2014-12-10
  • 1970-01-01
  • 2011-02-15
  • 1970-01-01
  • 2018-08-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多