Home > Back-end >  How to set default value of tkinter checkboxtreeview to "checked"
How to set default value of tkinter checkboxtreeview to "checked"

Time:11-16

I created a checkbox treeview with ttkwidgets. 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()

CodePudding user response:

Looking into the ttkwidgets source code for the CheckboxTreeview widget here, I found this change_state method

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

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

CodePudding user response:

According to the source code for CheckboxTreeview, you can set tags=("checked",) to make the checkbox checked initially when calling .insert(...):

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

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