Select multiple entries in Tkinter treeview without pressing ctrl key

若如初见. 提交于 2019-12-13 03:15:45

问题


I am trying to select multiple entries from Tkinter treeview. I used selectmode = extended for the same(use ctrl+enter key). But as soon as I try to open new branch in the tree(ctrl pressed), I am not able to open and if I do the same without pressing ctrl my selections from branch 1 disappears.

Hence, I am trying to get some other way for selecting multiple nodes from Tkinter tree (from different brances) without pressing ctrl key. (i.e either remembering my mouse selections or some checkbox or any other suggestion)

  • Here is a working code example which works for multiple selection in different branches using ctrl key but I need multiple selection for selecting nodes in different branches without pressing ctrl as using this I am not able to open new branch after selecting first one and if released nodes opens but choices disappears.

code:

import ttk
import Tkinter as tk

def select():
    for i in tree.selection():
        item_iid = i
        print "".join([str(tree.item(i)['text'])])# for i in curItems])


root = tk.Tk()
tree = ttk.Treeview(root,show="tree")#, selectmode=EXTENDED)  
tree.config(columns=("col1"))

#SUb treeview
style = ttk.Style(root)
style.configure("Treeview")
tree.configure(style="Treeview")

tree.insert("", "0", "item1", text="Branch1",)
tree.insert("", "1", "item2", text="Branch2")

#sub tree using item attribute to achieve that
tree.insert("item1", "1", text="FRED")
tree.insert("item1", "1", text="MAVIS")
tree.insert("item1", "1", text="BRIGHT")

tree.insert("item2", "2", text="SOME")
tree.insert("item2", "2", text="NODES")
tree.insert("item2", "2", text="HERE")

tree.pack(fill=tk.BOTH, expand=True)
tree.bind("<Return>", lambda e: select()) 

root.mainloop()

Expected: Select multiple nodes from different branches without pressing ctrl key


回答1:


The first thing you need to do is to set selectmode to None:

tree = ttk.Treeview(root,show="tree", selectmode="none")

From here onward you can handle the selection events yourself.

Now modify your select function to react on focus change:

def select(event=None):
    tree.selection_toggle(tree.focus())
    print tree.selection()

And finally bind it to a key you prefer, using mouse click as sample below:

tree.bind("<ButtonRelease-1>", select)


来源:https://stackoverflow.com/questions/58446788/select-multiple-entries-in-tkinter-treeview-without-pressing-ctrl-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!