Skip to main content
 首页 » 编程设计

python之检索 ttk.Treeview 项目的 'open' 选项作为 bool 值

2025年05月04日9emanlee

我在查询 (Python) ttk.Treeview item 的 open 选项时遇到了不良行为。可以通过执行以下操作来设置节点 (item) 的可见性:

tree.item(someItemID, open=True) # or 
tree.item(someItemID, open=False)  

我的假设是可以查询 open 选项以获得 bool 值 True/False。但是,情况似乎并非如此。考虑这个脚本:

from Tkinter import * 
from ttk import Treeview 
 
def check_state(): 
    for row in tree.get_children(): 
        opened = tree.item(row, option='open') 
        print row, 'opened:', opened, '(type: %s)' % str(type(opened)), 'Got:', 
        if not opened: 
            print 'False (bool)' 
        elif opened == 'true': 
            print 'equal to string "true"' 
        elif opened == 'false': 
            print 'equal to string "false"' 
        elif opened: 
            print 'True (bool)' 
        else: 
            print 'something entirely different(!)' 
    print 
 
win = Frame() 
tree = Treeview(win) 
win.pack() 
tree.pack() 
Button(win, text='View state', command=check_state).pack() 
 
 
level1 = ['C:\\dir1', 'C:\\dir2', 'C:\\dir3'] 
level2 = ['one.txt', 'two.txt', 'three.txt'] 
for L in level1: 
    iid = tree.insert('', END, text=L) 
    for M in level2: 
        tree.insert(iid, END, text=M) 
 
win.mainloop() 

运行时,它会显示一个小的 Treeview 控件,其中填充了假目录和文件名。 在打开或关闭任何顶级节点之前,按下按钮将打开 选项状态转储到标准输出。应该看起来像这样:

I001 opened: 0 (type: <type 'int'>) Got: False (bool) 
I005 opened: 0 (type: <type 'int'>) Got: False (bool) 
I009 opened: 0 (type: <type 'int'>) Got: False (bool) 

现在打开其中一个节点并再次按下按钮。现在它转储:

I001 opened: 0 (type: <type 'int'>) Got: False (bool) 
I005 opened: 0 (type: <type 'int'>) Got: False (bool) 
I009 opened: true (type: <type '_tkinter.Tcl_Obj'>) Got: True (bool) 

最后,关闭所有节点并再次按下按钮。它转储:

I001 opened: 0 (type: <type 'int'>) Got: False (bool) 
I005 opened: 0 (type: <type 'int'>) Got: False (bool) 
I009 opened: false (type: <type '_tkinter.Tcl_Obj'>) Got: True (bool) 

让我印象深刻的事情:

  1. 不一致:虽然初始化为int,但后来分配的值是_tkinter对象
  2. bool 比较失败:尽管 _tkinter 对象呈现为字符串“true”或“false”,但它们不会评估为 True 和 False(例如打印的 _tkinter 对象作为“假”评估为真)

有人知道是什么吗?如何可靠地确定 Treeview 项目的打开/关闭状态?

请您参考如下方法:

在 Barron Stone 的 Lynda 类(class)中,使用 Tkinter 进行 Python GUI 开发,类(class)视频,Building a hierarchical treeview ,有一个示例说明如何获取“已打开?”结果。我修改了下面的例子:

IDLE 控制台中的 Python 3.5

>>> from tkinter import * 
>>> from tkinter import ttk 
>>> root = Tk() 
>>> treeview = ttk.Treeview(root) 
>>> treeview.pack() 
>>> treeview.insert('', '0', 'par1', text = 'Parent') 
'par1' 
>>> treeview.insert('par1', '0', 'child1', text = 'Child') 
'child1' 
>>> treeview.item('par1', 'open') 
0 
>>> treeview.item('par1', open = True) 
{} 
>>> treeview.item('par1', 'open') 
1 
>>> 

不是要求的 bool 值,而是同样好的 int。