| 1 |
Tree |
| 2 |
==== |
| 3 |
|
| 4 |
Rich has a :class:`~rich.tree.Tree` class which can generate a tree view in the terminal. A tree view is a great way of presenting the contents of a filesystem or any other hierarchical data. Each branch of the tree can have a label which may be text or any other Rich renderable. |
| 5 |
|
| 6 |
Run the following command to see a demonstration of a Rich tree:: |
| 7 |
|
| 8 |
python -m rich.tree |
| 9 |
|
| 10 |
The following code creates and prints a tree with a simple text label:: |
| 11 |
|
| 12 |
from rich.tree import Tree |
| 13 |
from rich import print |
| 14 |
|
| 15 |
tree = Tree("Rich Tree") |
| 16 |
print(tree) |
| 17 |
|
| 18 |
With only a single ``Tree`` instance this will output nothing more than the text "Rich Tree". Things get more interesting when we call :meth:`~rich.tree.Tree.add` to add more branches to the Tree. The following code adds two more branches:: |
| 19 |
|
| 20 |
tree.add("foo") |
| 21 |
tree.add("bar") |
| 22 |
print(tree) |
| 23 |
|
| 24 |
The tree will now have two branches connected to the original tree with guide lines. |
| 25 |
|
| 26 |
When you call :meth:`~rich.tree.Tree.add` a new Tree instance is returned. You can use this instance to add more branches to, and build up a more complex tree. Let's add a few more levels to the tree:: |
| 27 |
|
| 28 |
baz_tree = tree.add("baz") |
| 29 |
baz_tree.add("[red]Red").add("[green]Green").add("[blue]Blue") |
| 30 |
print(tree) |
| 31 |
|
| 32 |
|
| 33 |
Tree Styles |
| 34 |
~~~~~~~~~~~ |
| 35 |
|
| 36 |
The Tree constructor and :meth:`~rich.tree.Tree.add` method allows you to specify a ``style`` argument which sets a style for the entire branch, and ``guide_style`` which sets the style for the guide lines. These styles are inherited by the branches and will apply to any sub-trees as well. |
| 37 |
|
| 38 |
If you set ``guide_style`` to bold, Rich will select the thicker variations of unicode line characters. Similarly, if you select the "underline2" style you will get double line style of unicode characters. |
| 39 |
|
| 40 |
|
| 41 |
Examples |
| 42 |
~~~~~~~~ |
| 43 |
|
| 44 |
For a more practical demonstration, see `tree.py <https://github.com/willmcgugan/rich/blob/master/examples/tree.py>`_ which can generate a tree view of a directory in your hard drive. |
| 45 |
|