Tree#

A widget for displaying a hierarchical tree of tabular data. Scroll bars will be provided if necessary.

../../../_images/tree-cocoa.png

Usage#

The simplest way to create a Tree is to pass a dictionary and a list of column headings. Each key in the dictionary can be either a tuple, whose contents will be mapped sequentially to the columns of a node, or a single object, which will be mapped to the first column. And each value in the dictionary can be either another dictionary containing the children of that node, or None if there are no children.

In this example, we will display a tree with 2 columns. The tree will have 2 root nodes; the first root node will have 1 child node; the second root node will have 2 children. The root nodes will only populate the “name” column; the other column will be blank:

import toga

tree = toga.Tree(
    headings=["Name", "Age"],
    data={
        "Earth": {
           ("Arthur Dent", 42): None,
        },
        "Betelgeuse Five": {
           ("Ford Prefect", 37): None,
           ("Zaphod Beeblebrox", 47): None,
        },
    }
)

# Get the details of the first child of the second root node:
print(f"{tree.data[1][0].name} is age {tree.data[1][0].age}")

# Append new data to the first root node in the tree
tree.data[0].append(("Tricia McMillan", 38))

You can also specify data for a Tree using a list of 2-tuples, with dictionaries providing data values. This allows you to store data in the data source that won’t be displayed in the tree. It also allows you to control the display order of columns independent of the storage of that data.

import toga

tree = toga.Tree(
    headings=["Name", "Age"],
    data=[
        (
            {"name": "Earth"},
            [({"name": "Arthur Dent", "age": 42, "status": "Anxious"}, None)]
        ),
        (
            {"name": "Betelgeuse Five"},
            [
                ({"name": "Ford Prefect", "age": 37, "status": "Hoopy"}, None),
                ({"name": "Zaphod Beeblebrox", "age": 47, "status": "Oblivious"}, None),
            ]
        ),
    ]
)

# Get the details of the first child of the second root node:
node = tree.data[1][0]
print(f"{node.name}, who is age {node.age}, is {node.status}")

The attribute names used on each row (called “accessors”) are created automatically from the headings, by:

  1. Converting the heading to lower case

  2. Removing any character that can’t be used in a Python identifier

  3. Replacing all whitespace with _

  4. Prepending _ if the first character is a digit

If you want to use different attributes, you can override them by providing an accessors argument. In this example, the tree will use “Name” as the visible header, but internally, the attribute “character” will be used:

import toga

tree = toga.Tree(
    headings=["Name", "Age"],
    accessors={"Name", 'character'},
    data=[
        (
            {"character": "Earth"},
            [({"character": "Arthur Dent", "age": 42, "status": "Anxious"}, None)]
        ),
        (
            {"character": "Betelgeuse Five"},
            [
                ({"character": "Ford Prefect", "age": 37, "status": "Hoopy"}, None),
                ({"character": "Zaphod Beeblebrox", "age": 47, "status": "Oblivious"}, None),
            ]
        ),
    ]
)

# Get the details of the first child of the second root node:
node = tree.data[1][0]
print(f"{node.character}, who is age {node.age}, is {node.status}")

The value provided by an accessor is interpreted as follows:

  • If the value is a Widget, that widget will be displayed in the cell. Note that this is currently a beta API: see the Notes section.

  • If the value is a tuple, it must have two elements: an icon, and a second element which will be interpreted as one of the options below.

  • If the value is None, then missing_value will be displayed.

  • Any other value will be converted into a string. If an icon has not already been provided in a tuple, it can also be provided using the value’s icon attribute.

Icon values must either be an Icon, which will be displayed on the left of the cell, or None to display no icon.

Notes#

  • Widgets in cells is a beta API which may change in future, and is currently only supported on macOS.

  • On macOS, you cannot change the font used in a Tree.

Reference#

class toga.Tree(headings=None, id=None, style=None, data=None, accessors=None, multiple_select=False, on_select=None, on_activate=None, missing_value='', on_double_click=None)#

Bases: Widget

Create a new Tree widget.

Parameters:
  • headings (list[str] | None) –

    The column headings for the tree. Headings can only contain one line; any text after a newline will be ignored.

    A value of None will produce a table without headings. However, if you do this, you must give a list of accessors.

  • id – The ID for the widget.

  • style – A style object. If no style is provided, a default style will be applied to the widget.

  • data (Any) – Initial data to be displayed in the tree.

  • accessors (list[str] | None) –

    Defines the attributes of the data source that will be used to populate each column. Must be either:

    • None to derive accessors from the headings, as described above; or

    • A list of the same size as headings, specifying the accessors for each heading. A value of None will fall back to the default generated accessor; or

    • A dictionary mapping headings to accessors. Any missing headings will fall back to the default generated accessor.

  • multiple_select (bool) – Does the tree allow multiple selection?

  • on_select (callable | None) – Initial on_select handler.

  • on_activate (callable | None) – Initial on_activate handler.

  • missing_value (str) – The string that will be used to populate a cell when the value provided by its accessor is None, or the accessor isn’t defined.

  • on_double_clickDEPRECATED; use on_activate.

property accessors: list[str]#

The accessors used to populate the tree (read-only)

append_column(heading, accessor=None)#

Append a column to the end of the tree.

Parameters:
  • heading (str) – The heading for the new column.

  • accessor (str | None) – The accessor to use on the data source when populating the tree. If not specified, an accessor will be derived from the heading.

collapse(node=None)#

Collapse the specified node of the tree.

If no node is provided, all nodes of the tree will be collapsed.

If the provided node is a leaf node, or the node is already collapsed, this is a no-op.

Parameters:

node (Node | None) – The node to collapse

property data: TreeSource#

The data to display in the tree.

When setting this property:

  • A Source will be used as-is. It must either be a TreeSource, or a custom class that provides the same methods.

  • A value of None is turned into an empty TreeSource.

  • Otherwise, the value must be an dictionary or an iterable, which is copied into a new TreeSource as shown here.

property enabled: bool#

Is the widget currently enabled? i.e., can the user interact with the widget? Tree widgets cannot be disabled; this property will always return True; any attempt to modify it will be ignored.

expand(node=None)#

Expand the specified node of the tree.

If no node is provided, all nodes of the tree will be expanded.

If the provided node is a leaf node, or the node is already expanded, this is a no-op.

If a node is specified, the children of that node will also be expanded.

Parameters:

node (Node | None) – The node to expand

focus()#

No-op; Tree cannot accept input focus

property headings: list[str]#

The column headings for the tree (read-only)

insert_column(index, heading, accessor=None)#

Insert an additional column into the tree.

Parameters:
  • index (int | str) – The index at which to insert the column, or the accessor of the column before which the column should be inserted.

  • heading (str | None) – The heading for the new column. If the tree doesn’t have headings, the value will be ignored.

  • accessor (str | None) – The accessor to use on the data source when populating the tree. If not specified, an accessor will be derived from the heading. An accessor must be specified if the tree doesn’t have headings.

property missing_value: str#

The value that will be used when a data row doesn’t provide an value for an attribute.

property multiple_select: bool#

Does the tree allow multiple rows to be selected?

property on_activate: callable#

The callback function that is invoked when a row of the tree is activated, usually with a double click or similar action.

property on_double_click#

Use on_activate

Type:

DEPRECATED

property on_select: callable#

The callback function that is invoked when a row of the tree is selected.

remove_column(column)#

Remove a tree column.

Parameters:

column (int | str) – The index of the column to remove, or the accessor of the column to remove.

property selection: list[Node] | Node | None#

The current selection of the tree.

If multiple selection is enabled, returns a list of Node objects from the data source matching the current selection. An empty list is returned if no nodes are selected.

If multiple selection is not enabled, returns the selected Node object, or None if no node is currently selected.