简体   繁体   English

如何将 tkinter checkboxtreeview 的默认值设置为“选中”

[英]How to set default value of tkinter checkboxtreeview to "checked"

I created a checkbox treeview with ttkwidgets.我用 ttkwidgets 创建了一个复选框 treeview。 I want these checkboxes to be "checked" by default.我希望默认情况下“选中”这些复选框。 How can I do that.我怎样才能做到这一点。

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()

Looking into the ttkwidgets source code for the CheckboxTreeview widget here , I found this change_state method 在这里查看CheckboxTreeview小部件的ttkwidgets源代码,我发现了这个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))

It seems like this is the intended way to set the check state for your treeview items, so you should be able to do this这似乎是为您的 treeview 项目设置支票 state 的预期方式,因此您应该能够执行此操作

tree.change_state(iid, 'checked')  # where 'iid' is the item id you want to modify

According to the source code for CheckboxTreeview , you can set tags=("checked",) to make the checkbox checked initially when calling .insert(...) :根据CheckboxTreeview的源代码,您可以设置tags=("checked",)以在调用.insert(...)时使复选框初始选中:

list = ["apple", "banana", "orange"]

for n, x in enumerate(list):
    tree.insert(parent="", index="end", iid=n,  text=x, tags=("checked",))

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

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