Skip to content

textual.dom

The module contains DOMNode, the base class for any object within the Textual Document Object Model, which includes all Widgets, Screens, and Apps.

QueryOneCacheKey module-attribute

QueryOneCacheKey = 'tuple[int, str, Type[Widget] | None]'

The key used to cache query_one results.

WalkMethod module-attribute

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

Valid walking methods for the DOMNode.walk_children method.

BadIdentifier

Bases: Exception

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

DOMError

Bases: Exception

Base exception class for errors relating to the DOM.

DOMNode

DOMNode(*, name=None, id=None, classes=None)

Bases: MessagePump

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

BINDINGS class-attribute

BINDINGS = []

A list of key bindings.

BINDING_GROUP_TITLE class-attribute instance-attribute

BINDING_GROUP_TITLE = None

Title of widget used where bindings are displayed (such as in the key panel).

COMPONENT_CLASSES class-attribute

COMPONENT_CLASSES = set()

Virtual DOM nodes, used to expose styles to line API widgets.

DEFAULT_CLASSES class-attribute

DEFAULT_CLASSES = ''

Default classes argument if not supplied.

DEFAULT_CSS class-attribute

DEFAULT_CSS = ''

Default TCSS.

HELP class-attribute

HELP = None

Optional help text shown in help panel (Markdown format).

SCOPED_CSS class-attribute

SCOPED_CSS = True

Should default css be limited to the widget type?

ancestors property

ancestors

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

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 property writable

auto_refresh

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

background_colors property

background_colors

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

Returns:

Type Description
tuple[Color, Color]

(<background color>, <color>)

children property

children

A view on to the children.

Returns:

Type Description
Sequence['Widget']

The node's children.

classes class-attribute instance-attribute

classes = _ClassesDescriptor()

CSS class names for this node.

colors property

colors

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

A CSS selector that identifies this DOM node.

css_identifier_styled property

css_identifier_styled

A syntax highlighted CSS identifier.

Returns:

Type Description
Text

A Rich Text object.

css_path_nodes property

css_path_nodes

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

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 property writable

display

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

The child nodes which will be displayed.

Returns:

Type Description
list[Widget]

A list of nodes.

id property writable

id

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

is_modal property

is_modal

Is the node a modal?

is_on_screen property

is_on_screen

Check if the node was displayed in the last screen update.

name property

name

The name of the node.

parent property

parent

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

A (frozen) set of all pseudo classes.

rich_style property

rich_style

Get a Rich Style object for this DOMNode.

Returns:

Type Description
Style

A Rich style.

screen property

screen

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

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

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 property writable

visible

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

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

action_toggle async

action_toggle(attribute_name)

Toggle an attribute on the node.

Assumes the attribute is a bool.

Parameters:

Name Type Description Default

attribute_name

str

Name of the attribute.

required

add_class

add_class(*class_names, update=True)

Add class names to this Node.

Parameters:

Name Type Description Default

*class_names

str

CSS class names to add.

()

update

bool

Also update styles.

True

Returns:

Type Description
Self

Self.

automatic_refresh

automatic_refresh()

Perform an automatic refresh.

This method is called when you set the auto_refresh attribute. You could implement this method if you want to perform additional work during an automatic refresh.

check_action

check_action(action, parameters)

Check whether an action is enabled.

Implement this method to add logic for dynamic actions / bindings.

Parameters:

Name Type Description Default

action

str

The name of an action.

required

parameters

tuple[object, ...]

A tuple of any action parameters.

required

Returns:

Type Description
bool | None

True if the action is enabled+visible, False if the action is disabled+hidden, None if the action is disabled+visible (grayed out in footer)

check_consume_key

check_consume_key(key, character)

Check if the widget may consume the given key.

This should be implemented in widgets that handle Key events and stop propagation (such as Input and TextArea).

Implementing this method will hide key bindings from the footer and key panel that would be consumed by the focused widget.

Parameters:

Name Type Description Default

key

str

A key identifier.

required

character

str | None

A character associated with the key, or None if there isn't one.

required

Returns:

Type Description
bool

True if the widget may capture the key in its Key event handler, or False if it won't.

data_bind

data_bind(*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

get_component_styles(*names)

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

Parameters:

Name Type Description Default

names

str

Names of the components.

()

Raises:

Type Description
KeyError

If the component class doesn't exist.

Returns:

Type Description
RenderStyles

A Styles object.

get_pseudo_classes

get_pseudo_classes()

Pseudo classes for a widget.

Returns:

Type Description
set[str]

Names of the pseudo classes.

has_class

has_class(*class_names)

Check if the Node has all the given class names.

Parameters:

Name Type Description Default

*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

has_pseudo_class(class_name)

Check the node has the given pseudo class.

Parameters:

Name Type Description Default

class_name

str

The pseudo class to check for.

required

Returns:

Type Description
bool

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

has_pseudo_classes

has_pseudo_classes(class_names)

Check the node has all the given pseudo classes.

Parameters:

Name Type Description Default

class_names

set[str]

Set of class names to check for.

required

Returns:

Type Description
bool

True if all pseudo class names are present.

mutate_reactive

mutate_reactive(reactive)

Force an update to a mutable reactive.

Example
self.reactive_name_list.append("Jessica")
self.mutate_reactive(MyClass.reactive_name_list)

Textual will automatically detect when a reactive is set to a new value, but it is unable to detect if a value is mutated (such as updating a list, dict, or attribute of an object). If you do wish to use a collection or other mutable object in a reactive, then you can call this method after your reactive is updated. This will ensure that all the reactive superpowers work.

Note

This method will cause watchers to be called, even if the value hasn't changed.

Parameters:

Name Type Description Default

reactive

Reactive[ReactiveType]

A reactive property (use the class scope syntax, i.e. MyClass.my_reactive).

required

notify_style_update

notify_style_update()

Called after styles are updated.

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

query

query(selector: str | None = None) -> DOMQuery[Widget]
query(selector=None)

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

Parameters:

Name Type Description Default

selector

str | type[QueryType] | None

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

None

Returns:

Type Description
DOMQuery[Widget] | DOMQuery[QueryType]

A query object.

query_children

query_children(
    selector: str | None = None,
) -> DOMQuery[Widget]
query_children(
    selector: type[QueryType],
) -> DOMQuery[QueryType]
query_children(selector=None)

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

Note that this will not return child widgets more than a single level deep. If you want to a query to potentially match all children in the widget tree, see query.

Parameters:

Name Type Description Default

selector

str | type[QueryType] | None

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

None

Returns:

Type Description
DOMQuery[Widget] | DOMQuery[QueryType]

A query object.

query_exactly_one

query_exactly_one(selector: str) -> Widget
query_exactly_one(selector: type[QueryType]) -> QueryType
query_exactly_one(
    selector: str, expect_type: type[QueryType]
) -> QueryType
query_exactly_one(selector, expect_type=None)

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

Note

This method is similar to query_one. The only difference is that it will raise TooManyMatches if there is more than a single match.

Parameters:

Name Type Description Default

selector

str | type[QueryType]

A selector or widget type.

required

expect_type

type[QueryType] | None

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

None

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 (and exactly_one==True).

Returns:

Type Description
QueryType | Widget

A widget matching the selector.

query_one

query_one(selector: str) -> Widget
query_one(selector: type[QueryType]) -> QueryType
query_one(selector, expect_type=None)

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

Parameters:

Name Type Description Default

selector

str | type[QueryType]

A selector or widget type.

required

expect_type

type[QueryType] | None

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

None

Raises:

Type Description
WrongType

If the wrong type was found.

NoMatches

If no node matches the query.

Returns:

Type Description
QueryType | Widget

A widget matching the selector.

refresh_bindings

refresh_bindings()

Call to prompt widgets such as the Footer to update the display of key bindings.

See actions for how to use this method.

remove_class

remove_class(*class_names, update=True)

Remove class names from this Node.

Parameters:

Name Type Description Default

*class_names

str

CSS class names to remove.

()

update

bool

Also update styles.

True

Returns:

Type Description
Self

Self.

reset_styles

reset_styles()

Reset styles back to their initial state.

run_worker

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

Name Type Description Default

work

WorkType[ResultType]

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

required

name

str | None

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

''

group

str

A short string to identify a group of workers.

'default'

description

str

A longer string to store longer information on the worker.

''

exit_on_error

bool

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

True

start

bool

Start the worker immediately.

True

exclusive

bool

Cancel all workers in the same group.

False

thread

bool

Mark the worker as a thread worker.

False

Returns:

Type Description
Worker[ResultType]

New Worker instance.

set_class

set_class(add, *class_names, update=True)

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

Parameters:

Name Type Description Default

add

bool

Add the classes if True, otherwise remove them.

required

update

bool

Also update styles.

True

Returns:

Type Description
Self

Self.

set_classes

set_classes(classes)

Replace all classes.

Parameters:

Name Type Description Default

classes

str | Iterable[str]

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

required

Returns:

Type Description
Self

Self.

set_reactive

set_reactive(reactive, value)

Sets a reactive value without invoking validators or watchers.

Example
self.set_reactive(App.theme, "textual-light")

Parameters:

Name Type Description Default

reactive

Reactive[ReactiveType]

A reactive property (use the class scope syntax, i.e. MyClass.my_reactive).

required

value

ReactiveType

New value of reactive.

required

Raises:

Type Description
AttributeError

If the first argument is not a reactive.

set_styles

set_styles(css=None, **update_styles)

Set custom styles on this object.

Parameters:

Name Type Description Default

css

str | None

Styles in CSS format.

None

update_styles

Any

Keyword arguments map style names onto style values.

{}

Returns:

Type Description
Self

Self.

sort_children

sort_children(*, 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:

Name Type Description Default

key

Callable[[Widget], SupportsRichComparison] | None

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

None

reverse

bool

Sort in descending order.

False

toggle_class

toggle_class(*class_names)

Toggle class names on this Node.

Parameters:

Name Type Description Default

*class_names

str

CSS class names to toggle.

()

Returns:

Type Description
Self

Self.

walk_children

walk_children(
    filter_type: type[WalkType],
    *,
    with_self: bool = False,
    method: WalkMethod = "depth",
    reverse: bool = False
) -> list[WalkType]
walk_children(
    *,
    with_self: bool = False,
    method: WalkMethod = "depth",
    reverse: bool = False
) -> list[DOMNode]
walk_children(
    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:

Name Type Description Default

filter_type

type[WalkType] | None

Filter only this type, or None for no filter.

None

with_self

bool

Also yield self in addition to descendants.

False

method

WalkMethod

One of "depth" or "breadth".

'depth'

reverse

bool

Reverse the order (bottom up).

False

Returns:

Type Description
list[DOMNode] | list[WalkType]

A list of nodes.

watch

Watches for modifications to reactive attributes on another object.

Example
def on_theme_change(old_value:str, new_value:str) -> None:
    # Called when app.theme changes.
    print(f"App.theme went from {old_value} to {new_value}")

self.watch(self.app, "theme", self.on_theme_change, init=False)

Parameters:

Name Type Description Default

obj

DOMNode

Object containing attribute to watch.

required

attribute_name

str

Attribute to watch.

required

callback

WatchCallbackType

A callback to run when attribute changes.

required

init

bool

Check watchers on first call.

True

NoScreen

Bases: DOMError

Raised when the node has no associated screen.

check_identifiers

check_identifiers(description, *names)

Validate identifier and raise an error if it fails.

Parameters:

Name Type Description Default

description

str

Description of where identifier is used for error message.

required

*names

str

Identifiers to check.

()