将 ttk.Treeview 项目的“打开”选项检索为布尔值

pat*_*ffe 3 python treeview tkinter ttk

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

tree.item(someItemID, open=True) # or
tree.item(someItemID, open=False) 
Run Code Online (Sandbox Code Playgroud)

我的假设是open可以查询该选项以获得布尔值 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()
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

对我来说突出的事情:

  1. 不一致:虽然初始化为ints,但后来分配的值是_tkinter对象
  2. 布尔比较失败:尽管_tkinter对象呈现为字符串“true”或“false”,但它们的计算结果并不为 True 和 False(例如,_tkinter打印为“false”的对象计算为 True)

有谁知道什么给?如何可靠地确定 Treeview 项的打开/关闭状态?

小智 5

在 Barron Stone 的 Lynda 课程“使用 Tkinter 进行 Python GUI 开发”的课程视频“构建分层树视图”中,有一个示例展示了如何获取“已打开?” 结果。我修改了下面的例子:

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
>>>
Run Code Online (Sandbox Code Playgroud)

不是所要求的布尔值,但也int同样好。