Skip to content

Tree

Added in version 0.6.0

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

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.

textual.widgets.Tree class

def __init__(
    self,
    label,
    data=None,
    *,
    name=None,
    id=None,
    classes=None,
    disabled=False
):

Bases: Generic[TreeDataType], ScrollView

A widget for displaying and navigating data in a tree.

Parameters
Parameter Default Description
label
TextType
required

The label of the root node of the tree.

data
TreeDataType | None
None

The optional data to associate with the root node of the tree.

name
str | None
None

The name of the Tree.

id
str | None
None

The ID of the tree in the DOM.

classes
str | None
None

The CSS classes of the tree.

disabled
bool
False

Whether the tree is disabled or not.

BINDINGS class-attribute

BINDINGS: list[BindingType] = [
    Binding("enter", "select_cursor", "Select", show=False),
    Binding("space", "toggle_node", "Toggle", show=False),
    Binding("up", "cursor_up", "Cursor Up", show=False),
    Binding(
        "down", "cursor_down", "Cursor Down", show=False
    ),
]
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 class-attribute

COMPONENT_CLASSES: set[str] = {
    "tree--cursor",
    "tree--guides",
    "tree--guides-hover",
    "tree--guides-selected",
    "tree--highlight",
    "tree--highlight-line",
    "tree--label",
}
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.

auto_expand instance-attribute class-attribute

auto_expand = var(True)

Auto expand tree nodes when clicked.

cursor_line instance-attribute class-attribute

cursor_line = var(-1, always_update=True)

The line with the cursor, or -1 if no cursor.

cursor_node property

cursor_node: TreeNode[TreeDataType] | None

The currently selected node, or None if no selection.

guide_depth instance-attribute class-attribute

guide_depth = reactive(4, init=False)

The indent depth of tree nodes.

hover_line instance-attribute class-attribute

hover_line = var(-1)

The line number under the mouse pointer, or -1 if not under the mouse pointer.

last_line property

last_line: int

The index of the last line.

root instance-attribute

root = self._add_node(None, text_label, data)

The root node of the tree.

show_guides instance-attribute class-attribute

show_guides = reactive(True)

Enable display of tree guide lines.

show_root instance-attribute class-attribute

show_root = reactive(True)

Show the root of the tree.

NodeCollapsed class

def __init__(self, node):

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.

control property

control: Tree[EventTreeDataType]

The tree that sent the message.

node instance-attribute

node: TreeNode[EventTreeDataType] = node

The node that was collapsed.

NodeExpanded class

def __init__(self, node):

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.

control property

control: Tree[EventTreeDataType]

The tree that sent the message.

node instance-attribute

node: TreeNode[EventTreeDataType] = node

The node that was expanded.

NodeHighlighted class

def __init__(self, node):

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.

control property

control: Tree[EventTreeDataType]

The tree that sent the message.

node instance-attribute

node: TreeNode[EventTreeDataType] = node

The node that was highlighted.

NodeSelected class

def __init__(self, node):

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.

control property

control: Tree[EventTreeDataType]

The tree that sent the message.

node instance-attribute

node: TreeNode[EventTreeDataType] = node

The node that was selected.

action_cursor_down method

def action_cursor_down(self):

Move the cursor down one node.

action_cursor_up method

def action_cursor_up(self):

Move the cursor up one node.

action_page_down method

def action_page_down(self):

Move the cursor down a page's-worth of nodes.

action_page_up method

def action_page_up(self):

Move the cursor up a page's-worth of nodes.

action_scroll_end method

def action_scroll_end(self):

Move the cursor to the bottom of the tree.

Note

Here bottom means vertically, not branch depth.

action_scroll_home method

def action_scroll_home(self):

Move the cursor to the top of the tree.

action_select_cursor method

def action_select_cursor(self):

Cause a select event for the target node.

Note

If auto_expand is True use of this action on a non-leaf node will cause both an expand/collapse event to occur, as well as a selected event.

action_toggle_node method

def action_toggle_node(self):

Toggle the expanded state of the target node.

clear method

def clear(self):

Clear all nodes under root.

Returns
Type Description
Self

The Tree instance.

get_label_width method

def get_label_width(self, node):

Get the width of the nodes label.

The default behavior is to call render_node and return the cell length. This method may be overridden in a sub-class if it can be done more efficiently.

Parameters
Parameter Default Description
node
TreeNode[TreeDataType]
required

A node.

Returns
Type Description
int

Width in cells.

get_node_at_line method

def get_node_at_line(self, line_no):

Get the node for a given line.

Parameters
Parameter Default Description
line_no
int
required

A line number.

Returns
Type Description
TreeNode[TreeDataType] | None

A tree node, or None if there is no node at that line.

get_node_by_id method

def get_node_by_id(self, node_id):

Get a tree node by its ID.

Parameters
Parameter Default Description
node_id
NodeID
required

The ID of the node to get.

Returns
Type Description
TreeNode[TreeDataType]

The node associated with that ID.

Raises
Type Description
UnknownNodeID

Raised if the TreeNode ID is unknown.

process_label method

def process_label(self, label):

Process a str or Text value into a label.

Maybe overridden in a subclass to change how labels are rendered.

Parameters
Parameter Default Description
label
TextType
required

Label.

Returns
Type Description
Text

A Rich Text object.

render_label method

def render_label(self, node, base_style, style):

Render a label for the given node. Override this to modify how labels are rendered.

Parameters
Parameter Default Description
node
TreeNode[TreeDataType]
required

A tree node.

base_style
Style
required

The base style of the widget.

style
Style
required

The additional style for the label.

Returns
Type Description
Text

A Rich Text object containing the label.

reset method

def reset(self, label, data=None):

Clear the tree and reset the root node.

Parameters
Parameter Default Description
label
TextType
required

The label for the root node.

data
TreeDataType | None
None

Optional data for the root node.

Returns
Type Description
Self

The Tree instance.

scroll_to_line method

def scroll_to_line(self, line, animate=True):

Scroll to the given line.

Parameters
Parameter Default Description
line
int
required

A line number.

animate
bool
True

Enable animation.

scroll_to_node method

def scroll_to_node(self, node, animate=True):

Scroll to the given node.

Parameters
Parameter Default Description
node
TreeNode[TreeDataType]
required

Node to scroll in to view.

animate
bool
True

Animate scrolling.

select_node method

def select_node(self, node):

Move the cursor to the given node, or reset cursor.

Parameters
Parameter Default Description
node
TreeNode[TreeDataType] | None
required

A tree node, or None to reset cursor.

validate_cursor_line method

def validate_cursor_line(self, value):

Prevent cursor line from going outside of range.

Parameters
Parameter Default Description
value
int
required

The value to test.

Return

A valid version of the given value.

validate_guide_depth method

def validate_guide_depth(self, value):

Restrict guide depth to reasonable range.

Parameters
Parameter Default Description
value
int
required

The value to test.

Return

A valid version of the given value.


Make non-widget Tree support classes available.

EventTreeDataType module-attribute

EventTreeDataType = TypeVar('EventTreeDataType')

The type of the data for a given instance of a Tree.

Similar to TreeDataType but used for Tree messages.

NodeID module-attribute

NodeID = NewType('NodeID', int)

The type of an ID applied to a TreeNode.

TreeDataType module-attribute

TreeDataType = TypeVar('TreeDataType')

The type of the data for a given instance of a Tree.

RemoveRootError class

Bases: Exception

Exception raised when trying to remove the root of a TreeNode.

TreeNode class

def __init__(
    self,
    tree,
    parent,
    id,
    label,
    data=None,
    *,
    expanded=True,
    allow_expand=True
):

Bases: Generic[TreeDataType]

An object that represents a "node" in a tree control.

Parameters
Parameter Default Description
tree
Tree[TreeDataType]
required

The tree that the node is being attached to.

parent
TreeNode[TreeDataType] | None
required

The parent node that this node is being attached to.

id
NodeID
required

The ID of the node.

label
Text
required

The label for the node.

data
TreeDataType | None
None

Optional data to associate with the node.

expanded
bool
True

Should the node be attached in an expanded state?

allow_expand
bool
True

Should the node allow being expanded by the user?

allow_expand writable property

allow_expand: bool

Is this node allowed to expand?

children property

children: TreeNodes[TreeDataType]

The child nodes of a TreeNode.

data instance-attribute

data = data

Optional data associated with the tree node.

id property

id: NodeID

The ID of the node.

is_expanded property

is_expanded: bool

Is the node expanded?

is_last property

is_last: bool

Is this the last child node of its parent?

is_root property

is_root: bool

Is this node the root of the tree?

label writable property

label: TextType

The label for the node.

line property

line: int

The line number for this node, or -1 if it is not displayed.

parent property

parent: TreeNode[TreeDataType] | None

The parent of the node.

tree property

tree: Tree[TreeDataType]

The tree that this node is attached to.

add method

def add(
    self,
    label,
    data=None,
    *,
    expand=False,
    allow_expand=True
):

Add a node to the sub-tree.

Parameters
Parameter Default Description
label
TextType
required

The new node's label.

data
TreeDataType | None
None

Data associated with the new node.

expand
bool
False

Node should be expanded.

allow_expand
bool
True

Allow use to expand the node via keyboard or mouse.

Returns
Type Description
TreeNode[TreeDataType]

A new Tree node

add_leaf method

def add_leaf(self, label, data=None):

Add a 'leaf' node (a node that can not expand).

Parameters
Parameter Default Description
label
TextType
required

Label for the node.

data
TreeDataType | None
None

Optional data.

Returns
Type Description
TreeNode[TreeDataType]

New node.

collapse method

def collapse(self):

Collapse the node (hide its children).

Returns
Type Description
Self

The TreeNode instance.

collapse_all method

def collapse_all(self):

Collapse the node (hide its children) and all those below it.

Returns
Type Description
Self

The TreeNode instance.

expand method

def expand(self):

Expand the node (show its children).

Returns
Type Description
Self

The TreeNode instance.

expand_all method

def expand_all(self):

Expand the node (show its children) and all those below it.

Returns
Type Description
Self

The TreeNode instance.

refresh method

def refresh(self):

Initiate a refresh (repaint) of this node.

remove method

def remove(self):

Remove this node from the tree.

Raises
Type Description
RemoveRootError

If there is an attempt to remove the root.

remove_children method

def remove_children(self):

Remove any child nodes of this node.

set_label method

def set_label(self, label):

Set a new label for the node.

Parameters
Parameter Default Description
label
TextType
required

A str or Text object with the new label.

toggle method

def toggle(self):

Toggle the node's expanded state.

Returns
Type Description
Self

The TreeNode instance.

toggle_all method

def toggle_all(self):

Toggle the node's expanded state and make all those below it match.

Returns
Type Description
Self

The TreeNode instance.

UnknownNodeID class

Bases: Exception

Exception raised when referring to an unknown TreeNode ID.