Skip to content

Tree

A hierarchical tree of tabular data.

Tree on macOS

Tree on Linux (GTK)

Tree on Linux (Qt)

Tree on Windows

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(
    columns=["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(
    columns=["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 strings for the headings are translated into AccessorColumn objects which tell the Tree how to get the values to display in the column by looking up attributes on the nodes.

The 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 attributes which don't match the headings, you can override them by providing your own AccessorColumn objects. In this example, the table will use "Name" as the visible header, but internally, the attribute "character" will be used:

import toga

tree = toga.Tree(
    columns=[AccessorColumn("Name", 'character'), "Age"],
    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. A tuple of any other length will raise an error.
  • 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.

So, for example:

import toga

green_icon = toga.Icon("icons/green")

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

will display a green icon next to "Earth", and nothing next to "Betelgeuse Five".

The AccessorColumn class is the only column class provided in core Toga, but you can define your own custom columns that implement the ColumnT protocol and there is a Column abstract base class that serves as a useful starting point. These columns can do things like giving you better control over getting icons and text, formatting in a particular way, combining multiple attributes to produce the value to display, or even accessing data via indexes rather than attribute lookup.

Sometimes when supplying rows using lists or other sequences, the order of the columns may not match the order of the data in the rows. In this case, the easiest approach is to create a [TreeSource][toga.sources.TreeSource] that maps the rows to the column accessors:

import toga

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

For more complex data you can define your own custom data sources.

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(
    columns: Iterable[str | ColumnT[Value]] | None = None,
    id: str | None = None,
    style: Pack | None = None,
    data: TreeSourceT | object | None = None,
    accessors: Iterable[str] | None = None,
    multiple_select: bool = False,
    on_select: OnSelectHandler | None = None,
    on_activate: OnActivateHandler | None = None,
    missing_value: str = "",
    *,
    show_headings: bool | None = None,
    headings: Iterable[str] | None = None,
    **kwargs,
)

Bases: Widget

Create a new Tree widget.

PARAMETER DESCRIPTION
columns

The column objects or heading strings for the tree. Column objects must implement the 'ColumnT' protocol. Heading strings will be converted to 'AccessorColumn' instances automatically. Heading strings can only contain one line; any text after a newline will be ignored.

DEPRECATED: A value of None will produce a table without headings. Rather than specifying a value of None for columns, you should use show_headings=False. However, if you do specify None for columns, you must provide a list of accessors.

TYPE: Iterable[str | ColumnT[Value]] | 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. This can be an object which implements the TreeSourceT protocol, an Iterable object, or None. An Iterable object will be automatically converted to a TreeSource.

TYPE: TreeSourceT | object | None DEFAULT: None

accessors

DEPRECATED To specify a non-default accessor name for a column, specify columns using 'AccessorColumn' instances. To specify the ordering of items in table data, specify data using a ListSource with an accessors argument.

When tree data is provided as an iterable, the TreeSource created by the Tree will try to derive its accessors from the column definitions. However, when the tree data has entries that will not be displayed in the tree, or when the autogenerated attribute for a column doesn't produce the required value, it may be necessary to override the list of accessors used to populate the table.

The accessors argument must be either:

  • A list at least as long as columns, specifying the accessors for each column and any additional accessors needed. When the column is given by a heading string then the heading and accessor will be used to create an AccessorColumn; or

  • A dictionary mapping heading strings to accessors. When the column is given by a heading string then the heading and accessor will be used to create an AccessorColumn. Any missing headings will fall back to the default generated accessor.

The default value of None results in accessors being derived from the columns.

If no columns or heading strings were provided, an 'AccessorColumn' instance will be created for each accessor and a tree with no headings will be created.

The accessors are also passed to any TreeSource created by the Tree to tell the source how to map lists and tuples to accessor values. This ordering does not change even when columns are added or removed.

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: ''

show_headings

Whether or not to show headings at the top of the tree. For backwards compatibility, this is set to False if no columns or headings are provided.

TYPE: bool | None DEFAULT: None

headings

DEPRECATED A list of heading strings for columns.

TYPE: Iterable[str] | None DEFAULT: None

kwargs

Initial style properties.

DEFAULT: {}

accessors property

accessors: list[str | None]

The list of column accessors (read-only) [Deprecated]

columns property

columns: list[ColumnT[Value]]

The columns for the tree (read-only)

data property writable

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.

In the last two cases, when creating a new or empty TreeSource, the accessors of the old source are copied to the new one or, if that is impossible, the accessors of the columns are used.

enabled property writable

enabled: Literal[True]

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: list[str] | None

The column headings for the tree (read-only)

missing_value property

missing_value: str

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

multiple_select property

multiple_select: bool

Does the tree allow multiple rows to be selected?

on_activate property writable

on_activate: OnActivateHandler

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: OnSelectHandler

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

selection 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.

show_headings property

show_headings: bool

Whether or not the table shows a header at the top (read-only)

append_column

append_column(
    column: ColumnT[Value] | str | None = None,
    accessor: str | None = None,
    *,
    heading: str | None = None,
) -> None

Append a column to the end of the tree.

PARAMETER DESCRIPTION
column

The new column, or a heading string for the new column.

TYPE: ColumnT[Value] | str | None DEFAULT: None

accessor

DEPRECATED To specify a non-default accessor for a column, use an AccessorColumn. To specify the ordering of accessors use a TreSource with an accessors argument for the data.

An accessor to use if a heading string is supplied rather than a column object. If not specified, an accessor will be derived from the heading. An accessor must be specified if the column is None.

TYPE: str | None DEFAULT: None

collapse

collapse(node: Node | None = None) -> 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: Node | None = None) -> 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: int | ColumnT[Value] | str,
    column: ColumnT[Value] | str | None = None,
    accessor: str | None = None,
    *,
    heading: str | None = None,
) -> None

Insert an additional column into the tree.

PARAMETER DESCRIPTION
index

The index at which to insert the column, or the column (or its accessor [Deprecated]) before which the new column should be inserted.

TYPE: int | ColumnT[Value] | str

column

The new column, or a heading string for the new column.

TYPE: ColumnT[Value] | str | None DEFAULT: None

accessor

DEPRECATED To specify a non-default accessor for a column, use an AccessorColumn. To specify the ordering of accessors use a TreSource with an accessors argument for the data.

An accessor to use if a heading string is supplied rather than a column object. If not specified, an accessor will be derived from the heading. An accessor must be specified if the column is None.

TYPE: str | None DEFAULT: None

remove_column

remove_column(column: int | ColumnT[Value] | str) -> None

Remove a tree column.

PARAMETER DESCRIPTION
column

The index of the column to remove, or the column (or its accessor [Deprecated]) to remove.

TYPE: int | ColumnT[Value] | str

toga.widgets.tree.OnSelectHandler

Bases: Protocol

__call__

__call__(widget: Tree, **kwargs: Any) -> None

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: Tree, **kwargs: Any) -> None

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: {}