我用 ttkwidgets 创建了一个复选框树视图。我希望默认情况下“选中”这些复选框。我怎样才能做到这一点。
from tkinter import *
from ttkwidgets import CheckboxTreeview
import tkinter as tk
root = tk.Tk()
tree = CheckboxTreeview(root)
tree.pack()
list = [("apple"), ("banana"), ("orange")]
n=0
for x in list:
tree.insert(parent="", index="end", iid=n, text=x)
n+=1
root.mainloop()
查看
ttkwidgets
小部件的CheckboxTreeview
源代码这里,我发现了这个change_state
方法
def change_state(self, item, state):
"""
Replace the current state of the item.
i.e. replace the current state tag but keeps the other tags.
:param item: item id
:type item: str
:param state: "checked", "unchecked" or "tristate": new state of the item
:type state: str
"""
tags = self.item(item, "tags")
states = ("checked", "unchecked", "tristate")
new_tags = [t for t in tags if t not in states]
new_tags.append(state)
self.item(item, tags=tuple(new_tags))
这似乎是为树视图项目设置检查状态的预期方法,因此您应该能够执行此操作
tree.change_state(iid, 'checked') # where 'iid' is the item id you want to modify
根据
CheckboxTreeview
的源码,可以设置tags=("checked",)
,使调用.insert(...)
时,复选框最初为checked:
list = ["apple", "banana", "orange"]
for n, x in enumerate(list):
tree.insert(parent="", index="end", iid=n, text=x, tags=("checked",))