Skip to content

Dom node

A DOMNode is a base class for any object within the Textual Document Object Model, which includes all Widgets, Screens, and Apps.

WalkMethod module-attribute

WalkMethod: TypeAlias = Literal['depth', 'breadth']

Valid walking methods for the DOMNode.walk_children method.

BadIdentifier class

Bases: Exception

Exception raised if you supply a id attribute or class name in the wrong format.

DOMError class

Bases: Exception

Base exception class for errors relating to the DOM.

DOMNode class

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

Bases: MessagePump

The base class for object that can be in the Textual DOM (App and Widget)

SCOPED_CSS class-attribute

SCOPED_CSS: bool = True

Should default css be limited to the widget type?

ancestors property

ancestors: list[DOMNode]

A list of ancestor nodes found by tracing a path all the way back to App.

Returns
Type Description
list[DOMNode]

A list of nodes.

ancestors_with_self property

ancestors_with_self: list[DOMNode]

A list of ancestor nodes found by tracing a path all the way back to App.

Note

This is inclusive of self.

Returns
Type Description
list[DOMNode]

A list of nodes.

auto_refresh writable property

auto_refresh: float | None

Number of seconds between automatic refresh, or None for no automatic refresh.

background_colors property

background_colors: tuple[Color, Color]

The background color and the color of the parent's background.

Returns
Type Description
tuple[Color, Color]

(<background color>, <color>)

children property

children: Sequence['Widget']

A view on to the children.

Returns
Type Description
Sequence['Widget']

The node's children.

classes instance-attribute class-attribute

classes = _ClassesDescriptor()

CSS class names for this node.

colors property

colors: tuple[Color, Color, Color, Color]

The widget's background and foreground colors, and the parent's background and foreground colors.

Returns
Type Description
tuple[Color, Color, Color, Color]

(<parent background>, <parent color>, <background>, <color>)

css_identifier property

css_identifier: str

A CSS selector that identifies this DOM node.

css_identifier_styled property

css_identifier_styled: Text

A syntax highlighted CSS identifier.

Returns
Type Description
Text

A Rich Text object.

css_path_nodes property

css_path_nodes: list[DOMNode]

A list of nodes from the App to this node, forming a "path".

Returns
Type Description
list[DOMNode]

A list of nodes, where the first item is the App, and the last is this node.

css_tree property

css_tree: Tree

A Rich tree to display the DOM, annotated with the node's CSS.

Log this to visualize your app in the textual console.

Example
self.log(self.css_tree)
Returns
Type Description
Tree

A Tree renderable.

display writable property

display: bool

Should the DOM node be displayed?

May be set to a boolean to show or hide the node, or to any valid value for the display rule.

Example
my_widget.display = False  # Hide my_widget

displayed_children property

displayed_children: list[Widget]

The child nodes which will be displayed.

Returns
Type Description
list[Widget]

A list of nodes.

id writable property

id: str | None

The ID of this node, or None if the node has no ID.

is_modal property

is_modal: bool

Is the node a modal?

name property

name: str | None

The name of the node.

parent property

parent: DOMNode | None

The parent node.

All nodes have parent once added to the DOM, with the exception of the App which is the root node.

pseudo_classes property

pseudo_classes: frozenset[str]

A (frozen) set of all pseudo classes.

rich_style property

rich_style: Style

Get a Rich Style object for this DOMNode.

Returns
Type Description
Style

A Rich style.

screen property

screen: 'Screen[object]'

The screen containing this node.

Returns
Type Description
'Screen[object]'

A screen object.

Raises
Type Description
NoScreen

If this node isn't mounted (and has no screen).

text_style property

text_style: Style

Get the text style object.

A widget's style is influenced by its parent. for instance if a parent is bold, then the child will also be bold.

Returns
Type Description
Style

A Rich Style.

tree property

tree: Tree

A Rich tree to display the DOM.

Log this to visualize your app in the textual console.

Example
self.log(self.tree)
Returns
Type Description
Tree

A Tree renderable.

visible writable property

visible: bool

Is this widget visible in the DOM?

If a widget hasn't had its visibility set explicitly, then it inherits it from its DOM ancestors.

This may be set explicitly to override inherited values. The valid values include the valid values for the visibility rule and the booleans True or False, to set the widget to be visible or invisible, respectively.

When a node is invisible, Textual will reserve space for it, but won't display anything.

workers property

workers: WorkerManager

The app's worker manager. Shortcut for self.app.workers.

action_toggle async

def action_toggle(self, attribute_name):

Toggle an attribute on the node.

Assumes the attribute is a bool.

Parameters
Parameter Default Description
attribute_name
str
required

Name of the attribute.

add_class method

def add_class(self, *class_names, update=True):

Add class names to this Node.

Parameters
Parameter Default Description
*class_names
str
()

CSS class names to add.

update
bool
True

Also update styles.

Returns
Type Description
Self

Self.

data_bind method

def data_bind(self, *reactives, **bind_vars):

Bind reactive data so that changes to a reactive automatically change the reactive on another widget.

Reactives may be given as positional arguments or keyword arguments. See the guide on data binding.

Example
def compose(self) -> ComposeResult:
    yield WorldClock("Europe/London").data_bind(WorldClockApp.time)
    yield WorldClock("Europe/Paris").data_bind(WorldClockApp.time)
    yield WorldClock("Asia/Tokyo").data_bind(WorldClockApp.time)
Raises
Type Description
ReactiveError

If the data wasn't bound.

Returns
Type Description
Self

Self.

get_component_styles method

def get_component_styles(self, name):

Get a "component" styles object (must be defined in COMPONENT_CLASSES classvar).

Parameters
Parameter Default Description
name
str
required

Name of the component.

Raises
Type Description
KeyError

If the component class doesn't exist.

Returns
Type Description
RenderStyles

A Styles object.

get_pseudo_classes method

def get_pseudo_classes(self):

Get any pseudo classes applicable to this Node, e.g. hover, focus.

Returns
Type Description
Iterable[str]

Iterable of strings, such as a generator.

has_class method

def has_class(self, *class_names):

Check if the Node has all the given class names.

Parameters
Parameter Default Description
*class_names
str
()

CSS class names to check.

Returns
Type Description
bool

True if the node has all the given class names, otherwise False.

has_pseudo_class method

def has_pseudo_class(self, class_name):

Check the node has the given pseudo class.

Parameters
Parameter Default Description
class_name
str
required

The pseudo class to check for.

Returns
Type Description
bool

True if the DOM node has the pseudo class, False if not.

has_pseudo_classes method

def has_pseudo_classes(self, class_names):

Check the node has all the given pseudo classes.

Parameters
Parameter Default Description
class_names
set[str]
required

Set of class names to check for.

Returns
Type Description
bool

True if all pseudo class names are present.

notify_style_update method

def notify_style_update(self):

Called after styles are updated.

Implement this in a subclass if you want to clear any cached data when the CSS is reloaded.

query method

def query(self, selector=None):

Query the DOM for children that match a selector or widget type.

Parameters
Parameter Default Description
selector
str | type[QueryType] | None
None

A CSS selector, widget type, or None for all nodes.

Returns
Type Description
DOMQuery[Widget] | DOMQuery[QueryType]

A query object.

query_one method

def query_one(self, selector, expect_type=None):

Get a widget from this widget's children that matches a selector or widget type.

Parameters
Parameter Default Description
selector
str | type[QueryType]
required

A selector or widget type.

expect_type
type[QueryType] | None
None

Require the object be of the supplied type, or None for any type.

Raises
Type Description
WrongType

If the wrong type was found.

NoMatches

If no node matches the query.

TooManyMatches

If there is more than one matching node in the query.

Returns
Type Description
QueryType | Widget

A widget matching the selector.

remove_class method

def remove_class(self, *class_names, update=True):

Remove class names from this Node.

Parameters
Parameter Default Description
*class_names
str
()

CSS class names to remove.

update
bool
True

Also update styles.

Returns
Type Description
Self

Self.

reset_styles method

def reset_styles(self):

Reset styles back to their initial state.

run_worker method

def run_worker(
    self,
    work,
    name="",
    group="default",
    description="",
    exit_on_error=True,
    start=True,
    exclusive=False,
    thread=False,
):

Run work in a worker.

A worker runs a function, coroutine, or awaitable, in the background as an async task or as a thread.

Parameters
Parameter Default Description
work
WorkType[ResultType]
required

A function, async function, or an awaitable object to run in a worker.

name
str | None
''

A short string to identify the worker (in logs and debugging).

group
str
'default'

A short string to identify a group of workers.

description
str
''

A longer string to store longer information on the worker.

exit_on_error
bool
True

Exit the app if the worker raises an error. Set to False to suppress exceptions.

start
bool
True

Start the worker immediately.

exclusive
bool
False

Cancel all workers in the same group.

thread
bool
False

Mark the worker as a thread worker.

Returns
Type Description
Worker[ResultType]

New Worker instance.

set_class method

def set_class(self, add, *class_names, update=True):

Add or remove class(es) based on a condition.

Parameters
Parameter Default Description
add
bool
required

Add the classes if True, otherwise remove them.

update
bool
True

Also update styles.

Returns
Type Description
Self

Self.

set_classes method

def set_classes(self, classes):

Replace all classes.

Parameters
Parameter Default Description
classes
str | Iterable[str]
required

A string containing space separated classes, or an iterable of class names.

Returns
Type Description
Self

Self.

set_reactive method

def set_reactive(self, reactive, value):

Sets a reactive value without invoking validators or watchers.

Example
self.set_reactive(App.dark_mode, True)
Parameters
Parameter Default Description
name
required

Name of reactive attribute.

value
ReactiveType
required

New value of reactive.

Raises
Type Description
AttributeError

If the first argument is not a reactive.

set_styles method

def set_styles(self, css=None, **update_styles):

Set custom styles on this object.

Parameters
Parameter Default Description
css
str | None
None

Styles in CSS format.

update_styles
Any
{}

Keyword arguments map style names onto style values.

Returns
Type Description
Self

Self.

sort_children method

def sort_children(self, *, key=None, reverse=False):

Sort child widgets with an optional key function.

If key is not provided then widgets will be sorted in the order they are constructed.

Example
# Sort widgets by name
screen.sort_children(key=lambda widget: widget.name or "")
Parameters
Parameter Default Description
key
Callable[[Widget], SupportsRichComparison] | None
None

A callable which accepts a widget and returns something that can be sorted, or None to sort without a key function.

reverse
bool
False

Sort in descending order.

toggle_class method

def toggle_class(self, *class_names):

Toggle class names on this Node.

Parameters
Parameter Default Description
*class_names
str
()

CSS class names to toggle.

Returns
Type Description
Self

Self.

walk_children method

def walk_children(
    self,
    filter_type=None,
    *,
    with_self=False,
    method="depth",
    reverse=False
):

Walk the subtree rooted at this node, and return every descendant encountered in a list.

Parameters
Parameter Default Description
filter_type
type[WalkType] | None
None

Filter only this type, or None for no filter.

with_self
bool
False

Also yield self in addition to descendants.

method
WalkMethod
'depth'

One of "depth" or "breadth".

reverse
bool
False

Reverse the order (bottom up).

Returns
Type Description
list[DOMNode] | list[WalkType]

A list of nodes.

watch method

def watch(self, obj, attribute_name, callback, init=True):

Watches for modifications to reactive attributes on another object.

Example

Here's how you could detect when the app changes from dark to light mode (and vice versa).

def on_dark_change(old_value:bool, new_value:bool):
    # Called when app.dark changes.
    print("App.dark when from {old_value} to {new_value}")

self.watch(self.app, "dark", self.on_dark_change, init=False)
Parameters
Parameter Default Description
obj
DOMNode
required

Object containing attribute to watch.

attribute_name
str
required

Attribute to watch.

callback
WatchCallbackType
required

A callback to run when attribute changes.

init
bool
True

Check watchers on first call.

NoScreen class

Bases: DOMError

Raised when the node has no associated screen.

check_identifiers function

def check_identifiers(description, *names):

Validate identifier and raise an error if it fails.

Parameters
Parameter Default Description
description
str
required

Description of where identifier is used for error message.

*names
str
()

Identifiers to check.