Skip to content

DirectoryTree

A tree control to navigate the contents of your filesystem.

  • Focusable
  • Container

Example

The example below creates a simple tree to navigate the current working directory.

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


class DirectoryTreeApp(App):
    def compose(self) -> ComposeResult:
        yield DirectoryTree("./")


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

Filtering

There may be times where you want to filter what appears in the DirectoryTree. To do this inherit from DirectoryTree and implement your own version of the filter_paths method. It should take an iterable of Python Path objects, and return those that pass the filter. For example, if you wanted to take the above code an filter out all of the "hidden" files and directories:

DirectoryTreeApp 📂  ┣━━ 📁 __pycache__ ┣━━ 📁 dist ┣━━ 📁 docs ┣━━ 📁 examples ┣━━ 📁 imgs ┣━━ 📁 notes ┣━━ 📁 questions ┣━━ 📁 reference ┣━━ 📁 sandbox ┣━━ 📁 site ┣━━ 📁 src ┣━━ 📁 tests ┣━━ 📁 tools ┣━━ 📄 CHANGELOG.md ┣━━ 📄 CODE_OF_CONDUCT.md ┣━━ 📄 CONTRIBUTING.md▄▄ ┣━━ 📄 docs.md ┣━━ 📄 faq.yml ┣━━ 📄 keys.log ┣━━ 📄 LICENSE ┣━━ 📄 Makefile ┣━━ 📄 mkdocs-common.yml ┣━━ 📄 mkdocs-nav-offline.yml

from pathlib import Path
from typing import Iterable

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


class FilteredDirectoryTree(DirectoryTree):
    def filter_paths(self, paths: Iterable[Path]) -> Iterable[Path]:
        return [path for path in paths if not path.name.startswith(".")]


class DirectoryTreeApp(App):
    def compose(self) -> ComposeResult:
        yield FilteredDirectoryTree("./")


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

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 directory tree widget inherits the bindings from the tree widget.

Component Classes

The directory tree widget provides the following component classes:

Class Description
directory-tree--extension Target the extension of a file name.
directory-tree--file Target files in the directory structure.
directory-tree--folder Target folders in the directory structure.
directory-tree--hidden Target hidden items in the directory structure.

See also the component classes for Tree.

See Also

  • Tree code reference

textual.widgets.DirectoryTree class

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

Bases: Tree[DirEntry]

A Tree widget that presents files and directories.

Parameters
Parameter Default Description
path
str | Path
required

Path to directory.

name
str | None
None

The name of the widget, or None for no name.

id
str | None
None

The ID of the widget in the DOM, or None for no ID.

classes
str | None
None

A space-separated list of classes, or None for no classes.

disabled
bool
False

Whether the directory tree is disabled or not.

COMPONENT_CLASSES class-attribute

COMPONENT_CLASSES: set[str] = {
    "directory-tree--extension",
    "directory-tree--file",
    "directory-tree--folder",
    "directory-tree--hidden",
}
Class Description
directory-tree--extension Target the extension of a file name.
directory-tree--file Target files in the directory structure.
directory-tree--folder Target folders in the directory structure.
directory-tree--hidden Target hidden items in the directory structure.

See also the component classes for Tree.

PATH class-attribute instance-attribute

PATH: Callable[[str | Path], Path] = Path

Callable that returns a fresh path object.

path class-attribute instance-attribute

path: var[str | Path] = path

The path that is the root of the directory tree.

Note

This can be set to either a str or a pathlib.Path object, but the value will always be a pathlib.Path object.

DirectorySelected class

def __init__(self, node, path):

Bases: Message

Posted when a directory is selected.

Can be handled using on_directory_tree_directory_selected in a subclass of DirectoryTree or in a parent widget in the DOM.

Parameters
Parameter Default Description
node
TreeNode[DirEntry]
required

The tree node for the directory that was selected.

path
Path
required

The path of the directory that was selected.

control property

control: Tree[DirEntry]

The Tree that had a directory selected.

node instance-attribute

node: TreeNode[DirEntry] = node

The tree node of the directory that was selected.

path instance-attribute

path: Path = path

The path of the directory that was selected.

FileSelected class

def __init__(self, node, path):

Bases: Message

Posted when a file is selected.

Can be handled using on_directory_tree_file_selected in a subclass of DirectoryTree or in a parent widget in the DOM.

Parameters
Parameter Default Description
node
TreeNode[DirEntry]
required

The tree node for the file that was selected.

path
Path
required

The path of the file that was selected.

control property

control: Tree[DirEntry]

The Tree that had a file selected.

node instance-attribute

node: TreeNode[DirEntry] = node

The tree node of the file that was selected.

path instance-attribute

path: Path = path

The path of the file that was selected.

clear_node method

def clear_node(self, node):

Clear all nodes under the given node.

Returns
Type Description
Self

The Tree instance.

filter_paths method

def filter_paths(self, paths):

Filter the paths before adding them to the tree.

Parameters
Parameter Default Description
paths
Iterable[Path]
required

The paths to be filtered.

Returns
Type Description
Iterable[Path]

The filtered paths.

By default this method returns all of the paths provided. To create a filtered DirectoryTree inherit from it and implement your own version of this method.

process_label method

def process_label(self, label):

Process a str or Text into a label. Maybe overridden in a subclass to modify how labels are rendered.

Parameters
Parameter Default Description
label
TextType
required

Label.

Returns
Type Description
Text

A Rich Text object.

reload method

def reload(self):

Reload the DirectoryTree contents.

Returns
Type Description
AwaitComplete

An optionally awaitable that ensures the tree has finished reloading.

reload_node method

def reload_node(self, node):

Reload the given node's contents.

The return value may be awaited to ensure the DirectoryTree has reached a stable state and is no longer performing any node reloading (of this node or any other nodes).

Parameters
Parameter Default Description
node
TreeNode[DirEntry]
required

The root of the subtree to reload.

Returns
Type Description
AwaitComplete

An optionally awaitable that ensures the subtree has finished reloading.

render_label method

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

Render a label for the given node.

Parameters
Parameter Default Description
node
TreeNode[DirEntry]
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_node method

def reset_node(self, node, label, data=None):

Clear the subtree and reset the given node.

Parameters
Parameter Default Description
node
TreeNode[DirEntry]
required

The node to reset.

label
TextType
required

The label for the node.

data
DirEntry | None
None

Optional data for the node.

Returns
Type Description
Self

The Tree instance.

validate_path method

def validate_path(self, path):

Ensure that the path is of the Path type.

Parameters
Parameter Default Description
path
str | Path
required

The path to validate.

Returns
Type Description
Path

The validated Path value.

Note

The result will always be a Python Path object, regardless of the value given.

watch_path async

def watch_path(self):

Watch for changes to the path of the directory tree.

If the path is changed the directory tree will be repopulated using the new value as the root.