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[str] = 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.

Bases: Generic[TreeDataType], ScrollView

A widget for displaying and navigating data in a tree.

Parameters:

Name Type Description Default

label

TextType

The label of the root node of the tree.

required

data

TreeDataType | None

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

None

name

str | None

The name of the Tree.

None

id

str | None

The ID of the tree in the DOM.

None

classes

str | None

The CSS classes of the tree.

None

disabled

bool

Whether the tree is disabled or not.

False

BINDINGS class-attribute

BINDINGS = [
    Binding(
        "shift+left",
        "cursor_parent",
        "Cursor to parent",
        show=False,
    ),
    Binding(
        "shift+right",
        "cursor_parent_next_sibling",
        "Cursor to next ancestor",
        show=False,
    ),
    Binding(
        "shift+up",
        "cursor_previous_sibling",
        "Cursor to previous sibling",
        show=False,
    ),
    Binding(
        "shift+down",
        "cursor_next_sibling",
        "Cursor to next sibling",
        show=False,
    ),
    Binding("enter", "select_cursor", "Select", show=False),
    Binding("space", "toggle_node", "Toggle", show=False),
    Binding(
        "shift+space",
        "toggle_expand_all",
        "Expand or collapse all",
        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 = {
    "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.

ICON_NODE class-attribute instance-attribute

ICON_NODE = 'â–¶ '

Unicode 'icon' to use for an expandable node.

ICON_NODE_EXPANDED class-attribute instance-attribute

ICON_NODE_EXPANDED = 'â–¼ '

Unicode 'icon' to use for an expanded node.

auto_expand class-attribute instance-attribute

auto_expand = var(True)

Auto expand tree nodes when they are selected.

center_scroll class-attribute instance-attribute

center_scroll = var(False)

Keep selected node in the center of the control, where possible.

cursor_line class-attribute instance-attribute

cursor_line = var(-1, always_update=True)

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

cursor_node property

cursor_node

The currently selected node, or None if no selection.

guide_depth class-attribute instance-attribute

guide_depth = reactive(4, init=False)

The indent depth of tree nodes.

hover_line class-attribute instance-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

The index of the last line.

root instance-attribute

root = _add_node(None, text_label, data)

The root node of the tree.

show_guides class-attribute instance-attribute

show_guides = reactive(True)

Enable display of tree guide lines.

show_root class-attribute instance-attribute

show_root = reactive(True)

Show the root of the tree.

NodeCollapsed

NodeCollapsed(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

The tree that sent the message.

node instance-attribute

node = node

The node that was collapsed.

NodeExpanded

NodeExpanded(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

The tree that sent the message.

node instance-attribute

node = node

The node that was expanded.

NodeHighlighted

NodeHighlighted(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

The tree that sent the message.

node instance-attribute

node = node

The node that was highlighted.

NodeSelected

NodeSelected(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

The tree that sent the message.

node instance-attribute

node = node

The node that was selected.

action_cursor_down

action_cursor_down()

Move the cursor down one node.

action_cursor_next_sibling

action_cursor_next_sibling()

Move the cursor to the next sibling, or to the paren't sibling if there are no more siblings.

action_cursor_parent

action_cursor_parent()

Move the cursor to the parent node.

action_cursor_parent_next_sibling

action_cursor_parent_next_sibling()

Move the cursor to the parent's next sibling.

action_cursor_previous_sibling

action_cursor_previous_sibling()

Move the cursor to previous sibling, or to the parent if there are no more siblings.

action_cursor_up

action_cursor_up()

Move the cursor up one node.

action_page_down

action_page_down()

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

action_page_up

action_page_up()

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

action_scroll_end

action_scroll_end()

Move the cursor to the bottom of the tree.

Note

Here bottom means vertically, not branch depth.

action_scroll_home

action_scroll_home()

Move the cursor to the top of the tree.

action_select_cursor

action_select_cursor()

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_expand_all

action_toggle_expand_all()

Expand or collapse all siblings.

If all the siblings are collapsed then they will be expanded. Otherwise they will all be collapsed.

action_toggle_node

action_toggle_node()

Toggle the expanded state of the target node.

add_json

add_json(json_data, node=None)

Adds JSON data to a node.

Parameters:

Name Type Description Default

json_data

object

An object decoded from JSON.

required

node

TreeNode | None

Node to add data to.

None

clear

clear()

Clear all nodes under root.

Returns:

Type Description
Self

The Tree instance.

get_label_width

get_label_width(node)

Get the width of the nodes label.

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

Parameters:

Name Type Description Default

node

TreeNode[TreeDataType]

A node.

required

Returns:

Type Description
int

Width in cells.

get_node_at_line

get_node_at_line(line_no)

Get the node for a given line.

Parameters:

Name Type Description Default

line_no

int

A line number.

required

Returns:

Type Description
TreeNode[TreeDataType] | None

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

get_node_by_id

get_node_by_id(node_id)

Get a tree node by its ID.

Parameters:

Name Type Description Default

node_id

NodeID

The ID of the node to get.

required

Returns:

Type Description
TreeNode[TreeDataType]

The node associated with that ID.

Raises:

Type Description
UnknownNodeID

Raised if the TreeNode ID is unknown.

move_cursor

move_cursor(node, animate=False)

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

Parameters:

Name Type Description Default

node

TreeNode[TreeDataType] | None

A tree node, or None to reset cursor.

required

animate

bool

Enable animation

False

move_cursor_to_line

move_cursor_to_line(line, animate=False)

Move the cursor to the given line.

Parameters:

Name Type Description Default

line

int

The line number (negative indexes are offsets from the last line).

required

animate

Enable scrolling animation.

False

Raises:

Type Description
IndexError

If the line doesn't exist.

process_label

process_label(label)

Process a str or Text value into a label.

May be overridden in a subclass to change how labels are rendered.

Parameters:

Name Type Description Default

label

TextType

Label.

required

Returns:

Type Description
Text

A Rich Text object.

render_label

render_label(node, base_style, style)

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

Parameters:

Name Type Description Default

node

TreeNode[TreeDataType]

A tree node.

required

base_style

Style

The base style of the widget.

required

style

Style

The additional style for the label.

required

Returns:

Type Description
Text

A Rich Text object containing the label.

reset

reset(label, data=None)

Clear the tree and reset the root node.

Parameters:

Name Type Description Default

label

TextType

The label for the root node.

required

data

TreeDataType | None

Optional data for the root node.

None

Returns:

Type Description
Self

The Tree instance.

scroll_to_line

scroll_to_line(line, animate=True)

Scroll to the given line.

Parameters:

Name Type Description Default

line

int

A line number.

required

animate

bool

Enable animation.

True

scroll_to_node

scroll_to_node(node, animate=True)

Scroll to the given node.

Parameters:

Name Type Description Default

node

TreeNode[TreeDataType]

Node to scroll in to view.

required

animate

bool

Animate scrolling.

True

select_node

select_node(node)

Move the cursor to the given node and select it, or reset cursor.

Parameters:

Name Type Description Default

node

TreeNode[TreeDataType] | None

A tree node to move the cursor to and select, or None to reset cursor.

required

unselect

unselect()

Hide and reset the cursor.

validate_cursor_line

validate_cursor_line(value)

Prevent cursor line from going outside of range.

Parameters:

Name Type Description Default

value

int

The value to test.

required
Return

A valid version of the given value.

validate_guide_depth

validate_guide_depth(value)

Restrict guide depth to reasonable range.

Parameters:

Name Type Description Default

value

int

The value to test.

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

AddNodeError

Bases: Exception

Exception raised when there is an error with a request to add a node.

RemoveRootError

Bases: Exception

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

TreeNode

TreeNode(
    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:

Name Type Description Default

tree

Tree[TreeDataType]

The tree that the node is being attached to.

required

parent

TreeNode[TreeDataType] | None

The parent node that this node is being attached to.

required

id

NodeID

The ID of the node.

required

label

Text

The label for the node.

required

data

TreeDataType | None

Optional data to associate with the node.

None

expanded

bool

Should the node be attached in an expanded state?

True

allow_expand

bool

Should the node allow being expanded by the user?

True

allow_expand property writable

allow_expand

Is this node allowed to expand?

children property

children

The child nodes of a TreeNode.

data instance-attribute

data = data

Optional data associated with the tree node.

id property

id

The ID of the node.

is_collapsed property

is_collapsed

Is the node collapsed?

is_expanded property

is_expanded

Is the node expanded?

is_last property

is_last

Is this the last child node of its parent?

is_root property

is_root

Is this node the root of the tree?

label property writable

label

The label for the node.

line property

line

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

next_sibling property

next_sibling

The next sibling below the node.

parent property

parent

The parent of the node.

previous_sibling property

previous_sibling

The previous sibling below the node.

siblings property

siblings

The siblings of this node (includes self).

tree property

tree

The tree that this node is attached to.

add

add(
    label,
    data=None,
    *,
    before=None,
    after=None,
    expand=False,
    allow_expand=True
)

Add a node to the sub-tree.

Parameters:

Name Type Description Default

label

TextType

The new node's label.

required

data

TreeDataType | None

Data associated with the new node.

None

before

int | TreeNode[TreeDataType] | None

Optional index or TreeNode to add the node before.

None

after

int | TreeNode[TreeDataType] | None

Optional index or TreeNode to add the node after.

None

expand

bool

Node should be expanded.

False

allow_expand

bool

Allow user to expand the node via keyboard or mouse.

True

Returns:

Type Description
TreeNode[TreeDataType]

A new Tree node

Raises:

Type Description
AddNodeError

If there is a problem with the addition request.

Note

Only one of before or after can be provided. If both are provided a AddNodeError will be raised.

add_leaf

add_leaf(label, data=None, *, before=None, after=None)

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

Parameters:

Name Type Description Default

label

TextType

Label for the node.

required

data

TreeDataType | None

Optional data.

None

before

int | TreeNode[TreeDataType] | None

Optional index or TreeNode to add the node before.

None

after

int | TreeNode[TreeDataType] | None

Optional index or TreeNode to add the node after.

None

Returns:

Type Description
TreeNode[TreeDataType]

New node.

Raises:

Type Description
AddNodeError

If there is a problem with the addition request.

Note

Only one of before or after can be provided. If both are provided a AddNodeError will be raised.

collapse

collapse()

Collapse the node (hide its children).

Returns:

Type Description
Self

The TreeNode instance.

collapse_all

collapse_all()

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

Returns:

Type Description
Self

The TreeNode instance.

expand

expand()

Expand the node (show its children).

Returns:

Type Description
Self

The TreeNode instance.

expand_all

expand_all()

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

Returns:

Type Description
Self

The TreeNode instance.

refresh

refresh()

Initiate a refresh (repaint) of this node.

remove

remove()

Remove this node from the tree.

Raises:

Type Description
RemoveRootError

If there is an attempt to remove the root.

remove_children

remove_children()

Remove any child nodes of this node.

set_label

set_label(label)

Set a new label for the node.

Parameters:

Name Type Description Default

label

TextType

A str or Text object with the new label.

required

toggle

toggle()

Toggle the node's expanded state.

Returns:

Type Description
Self

The TreeNode instance.

toggle_all

toggle_all()

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

Returns:

Type Description
Self

The TreeNode instance.

UnknownNodeID

Bases: Exception

Exception raised when referring to an unknown TreeNode ID.