简体   繁体   English

预选某些行时,Ttk.Treeview 多选失败

[英]Ttk.Treeview multiple selection fails when some lines are preselected

I want to select multiple lines from a ttk.Treeview widget.我想从 ttk.Treeview 小部件中选择多行。 The minimal code which follows produces this window:下面的最小代码产生这个窗口:

ttk.Treeview 截图

Simply clicking in the window produces correct results.只需在窗口中单击即可产生正确的结果。 The resulting tree selection is printed when treeview_callback is called.调用treeview_callback时会打印生成的树选择。

However, <Cmd> clicking which should produce an extended selection does not work but only when the widget is first displayed.但是, <Cmd>单击应该产生扩展选择的选项不起作用,只有在小部件首次显示时才起作用。 The callback function is not called by the virtual event <<TreeviewSelect>> .回调函数不会被虚拟事件<<TreeviewSelect>>调用。 <Cmd> clicking can be made to work by a prior mouse selection without the <Cmd> key. <Cmd>单击可以通过先前的鼠标选择而<Cmd>无需<Cmd>键。

The failure is inconsistent.失败是不一致的。 It happens when the treeview is first shown.它发生在第一次显示树视图时。 After a number of <Cmd> clicks on the same color they start to register.在多次<Cmd>单击相同颜色后,它们开始注册。 The number of clicks varies but has always been less than twenty.点击次数各不相同,但始终少于二十次。 I have not been able to detect any pattern that might explain when it starts working.我无法检测到任何可以解释它何时开始工作的模式。 Once it has started working correctly no relapse into the failure mode has been noticed.一旦它开始正常工作,就没有注意到故障模式的复发。

"""Treeview selection error demo."""

import tkinter as tk
import tkinter.ttk as ttk


def treeview_callback(tree: ttk.Treeview):
   def print_color_selection(*args):
       print(f"{tree.selection()=}")
   return print_color_selection


gui = tk.Tk()

tree = ttk.Treeview(gui, columns=('colors',), height=6, selectmode='extended', 
                    show='tree')
tree.grid(column=0, row=0)
tree.tag_bind('colors', '<<TreeviewSelect>>', callback=treeview_callback(tree))

for color in ['blue', 'white', 'red', 'green', 'goldenrod']:
    tree.insert('', 'end', color, text=color, tags='colors')
tree.selection_add('white', 'red', 'green')

gui.mainloop()

The workaround I found is to set the focus on the first item before setting the selection:我发现的解决方法是在设置选择之前将焦点设置在第一项上:

import tkinter as tk
import tkinter.ttk as ttk


def treeview_callback(tree: ttk.Treeview):
   def print_color_selection(*args):
       print(f"{tree.selection()}")
   return print_color_selection


gui = tk.Tk()

tree = ttk.Treeview(gui, columns=('colors',), height=6, selectmode='extended', 
                    show='tree')
tree.grid(column=0, row=0)
tree.tag_bind('colors', '<<TreeviewSelect>>', callback=treeview_callback(tree))

for color in ['blue', 'white', 'red', 'green', 'goldenrod']:
    tree.insert('', 'end', color, text=color, tags='colors')

tree.focus('blue') # <- This gives focus to the first item
tree.selection_set('white', 'red', 'green')

gui.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM