Skip to content

Tree

A tree control widget.

  • Focusable
  • Container

Example

The example below creates a simple tree.

TreeApp ▼ Dune └── ▼ Characters ├── Paul ├── Jessica └── Chani

from textual.app import App, ComposeResult
from textual.widgets import Tree


class TreeApp(App):
    def compose(self) -> ComposeResult:
        tree: Tree[dict] = Tree("Dune")
        tree.root.expand()
        characters = tree.root.add("Characters", expand=True)
        characters.add_leaf("Paul")
        characters.add_leaf("Jessica")
        characters.add_leaf("Chani")
        yield tree


if __name__ == "__main__":
    app = TreeApp()
    app.run()

Tree widgets have a "root" attribute which is an instance of a TreeNode. Call add() or add_leaf() to add new nodes underneath the root. Both these methods return a TreeNode for the child which you can use to add additional levels.

Reactive Attributes

Name Type Default Description
show_root bool True Show the root node.
show_guides bool True Show guide lines between levels.
guide_depth int 4 Amount of indentation between parent and child.

Messages

NodeCollapsed

Bases: Generic[EventTreeDataType], Message

Event sent when a node is collapsed.

Can be handled using on_tree_node_collapsed in a subclass of Tree or in a parent node in the DOM.

Attributes:

Name Type Description
node TreeNode[EventTreeDataType]

The node that was collapsed.

NodeExpanded

Bases: Generic[EventTreeDataType], Message

Event sent when a node is expanded.

Can be handled using on_tree_node_expanded in a subclass of Tree or in a parent node in the DOM.

Attributes:

Name Type Description
node TreeNode[EventTreeDataType]

The node that was expanded.

NodeHighlighted

Bases: Generic[EventTreeDataType], Message

Event sent when a node is highlighted.

Can be handled using on_tree_node_highlighted in a subclass of Tree or in a parent node in the DOM.

Attributes:

Name Type Description
node TreeNode[EventTreeDataType]

The node that was highlighted.

NodeSelected

Bases: Generic[EventTreeDataType], Message

Event sent when a node is selected.

Can be handled using on_tree_node_selected in a subclass of Tree or in a parent node in the DOM.

Attributes:

Name Type Description
node TreeNode[EventTreeDataType]

The node that was selected.

Bindings

The tree widget defines the following bindings:

Key(s) Description
enter Select the current item.
space Toggle the expand/collapsed space of the current item.
up Move the cursor up.
down Move the cursor down.

Component Classes

The tree widget provides the following component classes:

Class Description
tree--cursor Targets the cursor.
tree--guides Targets the indentation guides.
tree--guides-hover Targets the indentation guides under the cursor.
tree--guides-selected Targets the indentation guides that are selected.
tree--highlight Targets the highlighted items.
tree--highlight-line Targets the lines under the cursor.
tree--label Targets the (text) labels of the items.

See Also