Skip to content
Toga
0.5.3.dev143+gabcc6cdb6

Tree

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

/reference/images/tree-cocoa.png

/reference/images/tree-gtk.png

Not supported

Not supported

Not supported

Not supported

Not supported

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}")

Accessor names (whether explicitly provided, or automatically generated from the header names) should be unique. If they are not, column data will be duplicated, as Toga has no way to tell which version of an accessor to use when populating data for a column.

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

toga.Tree

Tree(
    headings=None,
    id=None,
    style=None,
    data=None,
    accessors=None,
    multiple_select=False,
    on_select=None,
    on_activate=None,
    missing_value="",
    **kwargs,
)

Bases: Widget

Create a new Tree widget.

PARAMETER DESCRIPTION
headings

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.

TYPE: Iterable[str] | None DEFAULT: None

id

The ID for the widget.

TYPE: str | None DEFAULT: None

style

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

TYPE: Pack | None DEFAULT: None

data

Initial data to be displayed in the tree.

TYPE: TreeSourceT | object | None DEFAULT: None

accessors

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.

TYPE: Iterable[str] | None DEFAULT: None

multiple_select

Does the tree allow multiple selection?

TYPE: bool DEFAULT: False

on_select

Initial on_select handler.

TYPE: OnSelectHandler | None DEFAULT: None

on_activate

Initial on_activate handler.

TYPE: OnActivateHandler | None DEFAULT: None

missing_value

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.

TYPE: str DEFAULT: ''

kwargs

Initial style properties.

DEFAULT: {}

accessors property

accessors

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

data property writable

data

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 a dictionary or an iterable, which is copied into a new TreeSource as shown here.

enabled property writable

enabled

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.

headings property

headings

The column headings for the tree (read-only)

missing_value property

missing_value

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

multiple_select property

multiple_select

Does the tree allow multiple rows to be selected?

on_activate property writable

on_activate

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

on_select property writable

on_select

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

selection property

selection

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.

append_column

append_column(heading, accessor=None)

Append a column to the end of the tree.

PARAMETER DESCRIPTION
heading

The heading for the new column.

TYPE: str

accessor

The accessor to use on the data source when populating the tree. If not specified, an accessor will be derived from the heading.

TYPE: str | None DEFAULT: None

collapse

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.

PARAMETER DESCRIPTION
node

The node to collapse

TYPE: Node | None DEFAULT: None

expand

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.

PARAMETER DESCRIPTION
node

The node to expand

TYPE: Node | None DEFAULT: None

insert_column

insert_column(index, heading, accessor=None)

Insert an additional column into the tree.

PARAMETER DESCRIPTION
index

The index at which to insert the column, or the accessor of the column before which the column should be inserted.

TYPE: int | str

heading

The heading for the new column. If the tree doesn't have headings, the value will be ignored.

TYPE: str

accessor

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.

TYPE: str | None DEFAULT: None

remove_column

remove_column(column)

Remove a tree column.

PARAMETER DESCRIPTION
column

The index of the column to remove, or the accessor of the column to remove.

TYPE: int | str

toga.widgets.tree.OnSelectHandler

Bases: Protocol

__call__

__call__(widget, **kwargs)

A handler to invoke when the tree is selected.

PARAMETER DESCRIPTION
widget

The Tree that was selected.

TYPE: Tree

kwargs

Ensures compatibility with arguments added in future versions.

TYPE: Any DEFAULT: {}

toga.widgets.tree.OnActivateHandler

Bases: Protocol

__call__

__call__(widget, **kwargs)

A handler to invoke when the tree is activated.

PARAMETER DESCRIPTION
widget

The Tree that was activated.

TYPE: Tree

kwargs

Ensures compatibility with arguments added in future versions.

TYPE: Any DEFAULT: {}