在查询(Python)open
ttk.Treeview
的{{1}}选项时遇到不良行为。可以通过执行以下操作来设置节点(item
)的可见性:
item
我的假设是可以查询tree.item(someItemID, open=True) # or
tree.item(someItemID, open=False)
选项以获得布尔值True / False。但是,情况似乎并非如此。考虑一下这个脚本:
open
运行时,它会显示一个填充了假目录和文件名的小Treeview控件。 在打开或关闭任何顶级节点之前,按下按钮将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()
选项状态转储到stdout。应该是这样的:
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)
最后,关闭所有节点并再次按下按钮。它转储:
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)
时,后来分配的值为int
个对象_tkinter
个对象呈现为字符串'true'或'false',但它们不会评估为True和False(例如,打印为“false”的_tkinter
对象被评估为真)任何人都知道是什么给出的?如何可靠地确定Treeview项目的打开/关闭状态?
答案 0 :(得分:1)
在Barron Stone的Lynda课程中,使用Tkinter的Python GUI开发,课程视频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
>>>
不是所要求的布尔值,而是int
同样好。
答案 1 :(得分:0)
有一个tkinter选项:tkinter.wantObjects
有些人提议改为False。它应该使Tk不使用TCL_objs。但是当我尝试它时,TreeView看起来很破碎。
作为一种解决方法,我使用了BooleanVar:
open_opt = BooleanVar()
for row in tree.get_children():
open_opt.set(str(tree.item(row, option='open')))
opened = open_opt.get()
这种方式似乎对我有用