hamil_clever_sim.main_display.MainView§

class MainView(driver_class=None, css_path=None, watch_css=False)[source]§

Bases: App

Create an instance of an app.

Args:
driver_class: Driver class or None to auto-detect.

This will be used by some Textual tools.

css_path: Path to CSS or None to use the CSS_PATH class variable.

To load multiple CSS files, pass a list of strings or paths which will be loaded in order.

watch_css: Reload CSS if the files changed. This is set automatically if

you are using textual run with the dev switch.

Raises:

CssPathError: When the supplied CSS path(s) are an unexpected type.

Methods

action_add_class

An [action](/guide/actions) to add a CSS class to the selected widget.

action_back

An [action](/guide/actions) to go back to the previous screen (pop the current screen).

action_bell

An [action](/guide/actions) to play the terminal 'bell'.

action_check_bindings

An [action](/guide/actions) to handle a key press using the binding system.

action_command_palette

Show the Textual command palette.

action_focus

An [action](/guide/actions) to focus the given widget.

action_focus_next

An [action](/guide/actions) to focus the next widget.

action_focus_previous

An [action](/guide/actions) to focus the previous widget.

action_pop_screen

An [action](/guide/actions) to remove the topmost screen and makes the new topmost screen active.

action_push_screen

An [action](/guide/actions) to push a new screen on to the stack and make it active.

action_quit

An [action](/guide/actions) to quit the app as soon as possible.

action_remove_class

An [action](/guide/actions) to remove a CSS class from the selected widget.

action_screenshot

This [action](/guide/actions) will save an SVG file containing the current contents of the screen.

action_switch_mode

An [action](/guide/actions) that switches to the given mode..

action_switch_screen

An [action](/guide/actions) to switch screens.

action_toggle_class

An [action](/guide/actions) to toggle a CSS class on the selected widget.

action_toggle_dark

An [action](/guide/actions) to toggle dark mode.

add_class

Add class names to this Node.

add_mode

Adds a mode and its corresponding base screen to the app.

animate

Animate an attribute.

batch_update

A context manager to suspend all repaints until the end of the batch.

begin_capture_print

Capture content that is printed (or written to stdout / stderr).

bell

Play the console 'bell'.

bind

Bind a key to an action.

call_after_refresh

Schedule a callback to run after all messages are processed and the screen has been refreshed.

call_from_thread

Run a callable from another thread, and return the result.

call_later

Schedule a callback to run after all messages are processed in this object.

call_next

Schedule a callback to run immediately after processing the current message.

capture_mouse

Send all mouse events to the given widget or disable mouse capture.

check_bindings

Handle a key press.

check_idle

Prompt the message pump to call idle if the queue is empty.

check_message_enabled

Check if a given message is enabled (allowed to be sent).

clear_notifications

Clear all the current notifications.

compose

rtype:

Iterable[Widget]

compose_add_child

Add a node to children.

disable_messages

Disable message types from being processed.

dispatch_key

Dispatch a key event to method.

enable_messages

Enable processing of messages types.

end_capture_print

End capturing of prints.

exit

Exit the app, and return the supplied result.

export_screenshot

Export an SVG screenshot of the current screen.

get_child_by_id

Get the first child (immediate descendent) of this DOMNode with the given ID.

get_child_by_type

Get a child of a give type.

get_component_styles

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

get_css_variables

Get a mapping of variables used to pre-populate CSS.

get_driver_class

Get a driver class for this platform.

get_key_display

For a given key, return how it should be displayed in an app (e.g. in the Footer widget).

get_pseudo_classes

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

get_screen

Get an installed screen.

get_widget_at

Get the widget under the given coordinates.

get_widget_by_id

Get the first descendant widget with the given ID.

handle_simulation_run

rtype:

None

handle_tab_active

rtype:

None

has_class

Check if the Node has all the given class names.

has_pseudo_class

Check for pseudo classes (such as hover, focus etc)

install_screen

Install a screen.

is_mounted

Check if a widget is mounted.

is_screen_installed

Check if a given screen has been installed.

mount

Mount the given widgets relative to the app's screen.

mount_all

Mount widgets from an iterable.

notify

Create a notification.

notify_style_update

Called after styles are updated.

on_callback

rtype:

None

on_event

rtype:

None

on_timer

rtype:

None

panic

Exits the app and display error message(s).

pop_screen

Pop the current [screen](/guide/screens) from the stack, and switch to the previous screen.

post_display_hook

Called immediately after a display is done.

post_message

Posts a message on to this widget's queue.

prevent

A context manager to temporarily prevent the given message types from being posted.

push_screen

Push a new [screen](/guide/screens) on the screen stack, making it the current screen.

query

Get a DOM query matching a selector.

query_one

Get a single Widget matching the given selector or selector type.

refresh

rtype:

None

refresh_css

Refresh CSS.

remove_class

Remove class names from this Node.

remove_mode

Removes a mode from the app.

render

rtype:

Union[ConsoleRenderable, RichCast, str]

reset_styles

Reset styles back to their initial state.

run

Run the app.

run_action

Perform an [action](/guide/actions).

run_async

Run the app asynchronously.

run_test

An asynchronous context manager for testing apps.

run_worker

Run work in a worker.

save_screenshot

Save an SVG screenshot of the current screen.

set_class

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

set_classes

Replace all classes.

set_focus

Focus (or unfocus) a widget.

set_interval

Call a function at periodic intervals.

set_styles

Set custom styles on this object.

set_timer

Make a function call after a delay.

stop_animation

Stop an animation on an attribute.

switch_mode

Switch to a given mode.

switch_screen

Switch to another [screen](/guide/screens) by replacing the top of the screen stack with a new screen.

toggle_class

Toggle class names on this Node.

uninstall_screen

Uninstall a screen.

update_styles

Immediately update the styles of this node and all descendant nodes.

validate_sub_title

Make sure the sub-title is set to a string.

validate_title

Make sure the title is set to a string.

walk_children

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

watch

Watches for modifications to reactive attributes on another object.

watch_dark

Watches the dark bool.

Attributes

AUTO_FOCUS

A selector to determine what to focus automatically when a screen is activated.

BINDINGS

COMMANDS

Command providers used by the [command palette](/guide/command_palette).

COMPONENT_CLASSES

CSS

Inline CSS, useful for quick scripts.

CSS_PATH

File paths to load CSS from.

DEFAULT_CLASSES

DEFAULT_CSS

ENABLE_COMMAND_PALETTE

Should the [command palette][textual.command.CommandPalette] be enabled for the application?

ExpectType

MODES

Modes associated with the app and their base screens.

SCOPED_CSS

Should default css be limited to the widget type?

SCREENS

Screens associated with the app for the lifetime of the app.

SUB_TITLE

A class variable to set the default sub-title for the application.

TITLE

A class variable to set the default title for the application.

WalkType

ancestors

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

ancestors_with_self

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

animator

app

Get the current app.

auto_refresh

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

background_colors

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

children

A view onto the app's immediate children.

colors

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

css_identifier

A CSS selector that identifies this DOM node.

css_identifier_styled

A syntax highlighted CSS identifier.

css_path_nodes

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

css_tree

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

current_mode

The name of the currently active mode.

debug

Is debug mode enabled?

display

Should the DOM node be displayed?

displayed_children

The child nodes which will be displayed.

focused

The widget that is focused on the currently active screen, or None.

has_parent

Does this object have a parent?

id

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

is_attached

Is the node attached to the app via the DOM?

is_headless

Is the driver running in 'headless' mode?

is_modal

Is the node a modal?

is_parent_active

Is the parent active?

is_running

Is the message pump running (potentially processing messages)?

log

The textual logger.

name

The name of the node.

namespace_bindings

Get currently active bindings.

parent

The parent node.

pseudo_classes

A (frozen) set of all pseudo classes.

return_code

The return code with which the app exited.

return_value

The return value of the app, or None if it has not yet been set.

rich_style

Get a Rich Style object for this DOMNode.

screen

The current active screen.

screen_stack

A snapshot of the current screen stack.

size

The size of the terminal.

task

text_style

Get the text style object.

tree

A Rich tree to display the DOM.

visible

Is this widget visible in the DOM?

workers

The [worker](guide/workers/) manager.

title

The title for the application.

sub_title

The sub-title for the application.

dark

Use a dark theme if True, otherwise use a light theme.

cursor_position

The position of the terminal cursor in screen-space.

use_command_palette

A flag to say if the application should use the command palette.

scroll_sensitivity_x

Number of columns to scroll in the X direction with wheel or trackpad.

scroll_sensitivity_y

Number of lines to scroll in the Y direction with wheel or trackpad.

classes

CSS class names for this node.

async action_add_class(selector, class_name)§

An [action](/guide/actions) to add a CSS class to the selected widget.

Return type:

None

Args:

selector: Selects the widget to add the class to. class_name: The class to add to the selected widget.

async action_back()§

An [action](/guide/actions) to go back to the previous screen (pop the current screen).

Return type:

None

Note:

If there is no screen to go back to, this is a non-operation (in other words it’s safe to call even if there are no other screens on the stack.)

async action_bell()§

An [action](/guide/actions) to play the terminal ‘bell’.

Return type:

None

async action_check_bindings(key)§

An [action](/guide/actions) to handle a key press using the binding system.

Return type:

None

Args:

key: The key to process.

action_command_palette()§

Show the Textual command palette.

Return type:

None

async action_focus(widget_id)§

An [action](/guide/actions) to focus the given widget.

Return type:

None

Args:

widget_id: ID of widget to focus.

action_focus_next()§

An [action](/guide/actions) to focus the next widget.

Return type:

None

action_focus_previous()§

An [action](/guide/actions) to focus the previous widget.

Return type:

None

async action_pop_screen()§

An [action](/guide/actions) to remove the topmost screen and makes the new topmost screen active.

Return type:

None

async action_push_screen(screen)§

An [action](/guide/actions) to push a new screen on to the stack and make it active.

Return type:

None

Args:

screen: Name of the screen.

async action_quit()§

An [action](/guide/actions) to quit the app as soon as possible.

Return type:

None

async action_remove_class(selector, class_name)§

An [action](/guide/actions) to remove a CSS class from the selected widget.

Return type:

None

Args:

selector: Selects the widget to remove the class from. class_name: The class to remove from the selected widget.

action_screenshot(filename=None, path='./')§

This [action](/guide/actions) will save an SVG file containing the current contents of the screen.

Return type:

None

Args:

filename: Filename of screenshot, or None to auto-generate. path: Path to directory. Defaults to current working directory.

async action_switch_mode(mode)§

An [action](/guide/actions) that switches to the given mode..

Return type:

None

async action_switch_screen(screen)§

An [action](/guide/actions) to switch screens.

Return type:

None

Args:

screen: Name of the screen.

async action_toggle_class(selector, class_name)§

An [action](/guide/actions) to toggle a CSS class on the selected widget.

Return type:

None

Args:

selector: Selects the widget to toggle the class on. class_name: The class to toggle on the selected widget.

action_toggle_dark()§

An [action](/guide/actions) to toggle dark mode.

Return type:

None

add_class(*class_names)§

Add class names to this Node.

Return type:

Self

Args:

*class_names: CSS class names to add.

Returns:

Self.

add_mode(mode, base_screen)§

Adds a mode and its corresponding base screen to the app.

Return type:

None

Args:

mode: The new mode. base_screen: The base screen associated with the given mode.

Raises:

InvalidModeError: If the name of the mode is not valid/duplicated.

property ancestors: list[DOMNode]§

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

Returns:

A list of nodes.

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:

A list of nodes.

animate(attribute, value, *, final_value=Ellipsis, duration=None, speed=None, delay=0.0, easing='in_out_cubic', on_complete=None)§

Animate an attribute.

See the guide for how to use the [animation](/guide/animation) system.

Return type:

None

Args:

attribute: Name of the attribute to animate. value: The value to animate to. final_value: The final value of the animation. duration: The duration of the animate. speed: The speed of the animation. delay: A delay (in seconds) before the animation starts. easing: An easing method. on_complete: A callable to invoke when the animation is finished.

property app: App[object]§

Get the current app.

Returns:

The current app.

Raises:

NoActiveAppError: if no active app could be found for the current asyncio context

property auto_refresh: float | None§

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

property background_colors: tuple[Color, Color]§

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

Returns:

(<background color>, <color>)

batch_update()§

A context manager to suspend all repaints until the end of the batch.

Return type:

Generator[None, None, None]

begin_capture_print(target, stdout=True, stderr=True)§

Capture content that is printed (or written to stdout / stderr).

If printing is captured, the target will be sent an [events.Print][textual.events.Print] message.

Return type:

None

Args:

target: The widget where print content will be sent. stdout: Capture stdout. stderr: Capture stderr.

bell()§

Play the console ‘bell’.

For terminals that support a bell, this typically makes a notification or error sound. Some terminals may make no sound or display a visual bell indicator, depending on configuration.

Return type:

None

bind(keys, action, *, description='', show=True, key_display=None)§

Bind a key to an action.

Return type:

None

Args:

keys: A comma separated list of keys, i.e. action: Action to bind to. description: Short description of action. show: Show key in UI. key_display: Replacement text for key, or None to use default.

call_after_refresh(callback, *args, **kwargs)§

Schedule a callback to run after all messages are processed and the screen has been refreshed. Positional and keyword arguments are passed to the callable.

Return type:

bool

Args:

callback: A callable.

Returns:
True if the callback was scheduled, or False if the callback could not be

scheduled (may occur if the message pump was closed or closing).

call_from_thread(callback, *args, **kwargs)§

Run a callable from another thread, and return the result.

Like asyncio apps in general, Textual apps are not thread-safe. If you call methods or set attributes on Textual objects from a thread, you may get unpredictable results.

This method will ensure that your code runs within the correct context.

!!! tip :rtype: TypeVar(CallThreadReturnType)

Consider using [post_message][textual.message_pump.MessagePump.post_message] which is also thread-safe.

Args:

callback: A callable to run. *args: Arguments to the callback. **kwargs: Keyword arguments for the callback.

Raises:
RuntimeError: If the app isn’t running or if this method is called from the same

thread where the app is running.

Returns:

The result of the callback.

call_later(callback, *args, **kwargs)§

Schedule a callback to run after all messages are processed in this object. Positional and keywords arguments are passed to the callable.

Return type:

bool

Args:

callback: Callable to call next. *args: Positional arguments to pass to the callable. **kwargs: Keyword arguments to pass to the callable.

Returns:
True if the callback was scheduled, or False if the callback could not be

scheduled (may occur if the message pump was closed or closing).

call_next(callback, *args, **kwargs)§

Schedule a callback to run immediately after processing the current message.

Return type:

None

Args:

callback: Callable to run after current event. *args: Positional arguments to pass to the callable. **kwargs: Keyword arguments to pass to the callable.

capture_mouse(widget)§

Send all mouse events to the given widget or disable mouse capture.

Return type:

None

Args:

widget: If a widget, capture mouse event, or None to end mouse capture.

async check_bindings(key, priority=False)§

Handle a key press.

This method is used internally by the bindings system, but may be called directly if you wish to simulate a key being pressed.

Return type:

bool

Args:

key: A key. priority: If True check from App down, otherwise from focused up.

Returns:

True if the key was handled by a binding, otherwise False

check_idle()§

Prompt the message pump to call idle if the queue is empty.

Return type:

None

check_message_enabled(message)§

Check if a given message is enabled (allowed to be sent).

Return type:

bool

Args:

message: A message object.

Returns:

True if the message will be sent, or False if it is disabled.

property children: Sequence[Widget]§

A view onto the app’s immediate children.

This attribute exists on all widgets. In the case of the App, it will only ever contain a single child, which will be the currently active screen.

Returns:

A sequence of widgets.

classes§

CSS class names for this node.

clear_notifications()§

Clear all the current notifications.

Return type:

None

property colors: tuple[Color, Color, Color, Color]§

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

Returns:

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

compose_add_child(widget)§

Add a node to children.

This is used by the compose process when it adds children. There is no need to use it directly, but you may want to override it in a subclass if you want children to be attached to a different node.

Return type:

None

Args:

widget: A Widget to add.

property css_identifier: str§

A CSS selector that identifies this DOM node.

property css_identifier_styled: Text§

A syntax highlighted CSS identifier.

Returns:

A Rich Text object.

property css_path_nodes: list[DOMNode]§

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

Returns:

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

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:

`python self.log(self.css_tree) `

Returns:

A Tree renderable.

property current_mode: str§

The name of the currently active mode.

cursor_position§

The position of the terminal cursor in screen-space.

This can be set by widgets and is useful for controlling the positioning of OS IME and emoji popup menus.

dark: Reactive[bool]§

Use a dark theme if True, otherwise use a light theme.

Modify this attribute to switch between light and dark themes.

Example:

`python self.app.dark = not self.app.dark  # Toggle dark mode `

property debug: bool§

Is debug mode enabled?

disable_messages(*messages)§

Disable message types from being processed.

Return type:

None

async dispatch_key(event)§

Dispatch a key event to method.

This method will call the method named ‘key_<event.key>’ if it exists. Some keys have aliases. The first alias found will be invoked if it exists. If multiple handlers exist that match the key, an exception is raised.

Return type:

bool

Args:

event: A key event.

Returns:

True if key was handled, otherwise False.

Raises:

DuplicateKeyHandlers: When there’s more than 1 handler that could handle this key.

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:

`python my_widget.display = False  # Hide my_widget `

property displayed_children: list[Widget]§

The child nodes which will be displayed.

Returns:

A list of nodes.

enable_messages(*messages)§

Enable processing of messages types.

Return type:

None

end_capture_print(target)§

End capturing of prints.

Return type:

None

Args:

target: The widget that was capturing prints.

exit(result=None, return_code=0, message=None)§

Exit the app, and return the supplied result.

Return type:

None

Args:

result: Return value. return_code: The return code. Use non-zero values for error codes. message: Optional message to display on exit.

export_screenshot(*, title=None)§

Export an SVG screenshot of the current screen.

See also [save_screenshot][textual.app.App.save_screenshot] which writes the screenshot to a file.

Return type:

str

Args:
title: The title of the exported screenshot or None

to use app title.

property focused: Widget | None§

The widget that is focused on the currently active screen, or None.

Focused widgets receive keyboard input.

Returns:

The currently focused widget, or None if nothing is focused.

get_child_by_id(id, expect_type=None)§

Get the first child (immediate descendent) of this DOMNode with the given ID.

Return type:

ExpectType | Widget

Args:

id: The ID of the node to search for. expect_type: Require the object be of the supplied type,

or use None to apply no type restriction.

Returns:

The first child of this node with the specified ID.

Raises:

NoMatches: If no children could be found for this ID. WrongType: If the wrong type was found.

get_child_by_type(expect_type)§

Get a child of a give type.

Return type:

ExpectType

Args:

expect_type: The type of the expected child.

Raises:

NoMatches: If no valid child is found.

Returns:

A widget.

get_component_styles(name)§

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

Return type:

RenderStyles

Args:

name: Name of the component.

Raises:

KeyError: If the component class doesn’t exist.

Returns:

A Styles object.

get_css_variables()§

Get a mapping of variables used to pre-populate CSS.

May be implemented in a subclass to add new CSS variables.

Return type:

dict[str, str]

Returns:

A mapping of variable name to value.

get_driver_class()§

Get a driver class for this platform.

This method is called by the constructor, and unlikely to be required when building a Textual app.

Return type:

Type[Driver]

Returns:

A Driver class which manages input and display.

get_key_display(key)§

For a given key, return how it should be displayed in an app (e.g. in the Footer widget). By key, we refer to the string used in the “key” argument for a Binding instance. By overriding this method, you can ensure that keys are displayed consistently throughout your app, without needing to add a key_display to every binding.

Return type:

str

Args:

key: The binding key string.

Returns:

The display string for the input key.

get_pseudo_classes()§

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

Return type:

Iterable[str]

Returns:

Iterable of strings, such as a generator.

get_screen(screen)§

Get an installed screen.

Return type:

Screen

Args:

screen: Either a Screen object or screen name (the name argument when installed).

Raises:

KeyError: If the named screen doesn’t exist.

Returns:

A screen instance.

get_widget_at(x, y)§

Get the widget under the given coordinates.

Return type:

tuple[Widget, Region]

Args:

x: X coordinate. y: Y coordinate.

Returns:

The widget and the widget’s screen region.

get_widget_by_id(id, expect_type=None)§

Get the first descendant widget with the given ID.

Performs a breadth-first search rooted at the current screen. It will not return the Screen if that matches the ID. To get the screen, use self.screen.

Return type:

ExpectType | Widget

Args:

id: The ID to search for in the subtree expect_type: Require the object be of the supplied type, or None for any type.

Defaults to None.

Returns:

The first descendant encountered with this ID.

Raises:

NoMatches: if no children could be found for this ID WrongType: if the wrong type was found.

has_class(*class_names)§

Check if the Node has all the given class names.

Return type:

bool

Args:

*class_names: CSS class names to check.

Returns:

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

property has_parent: bool§

Does this object have a parent?

has_pseudo_class(*class_names)§

Check for pseudo classes (such as hover, focus etc)

Return type:

bool

Args:

*class_names: The pseudo classes to check for.

Returns:

True if the DOM node has those pseudo classes, False if not.

property id: str | None§

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

install_screen(screen, name)§

Install a screen.

Installing a screen prevents Textual from destroying it when it is no longer on the screen stack. Note that you don’t need to install a screen to use it. See [push_screen][textual.app.App.push_screen] or [switch_screen][textual.app.App.switch_screen] to make a new screen current.

Return type:

None

Args:

screen: Screen to install. name: Unique name to identify the screen.

Raises:

ScreenError: If the screen can’t be installed.

Returns:

An awaitable that awaits the mounting of the screen and its children.

property is_attached: bool§

Is the node attached to the app via the DOM?

property is_headless: bool§

Is the driver running in ‘headless’ mode?

Headless mode is used when running tests with [run_test][textual.app.App.run_test].

property is_modal: bool§

Is the node a modal?

is_mounted(widget)§

Check if a widget is mounted.

Return type:

bool

Args:

widget: A widget.

Returns:

True of the widget is mounted.

property is_parent_active: bool§

Is the parent active?

property is_running: bool§

Is the message pump running (potentially processing messages)?

is_screen_installed(screen)§

Check if a given screen has been installed.

Return type:

bool

Args:

screen: Either a Screen object or screen name (the name argument when installed).

Returns:

True if the screen is currently installed,

property log: Logger§

The textual logger.

Example:

`python self.log("Hello, World!") self.log(self.tree) `

Returns:

A Textual logger.

mount(*widgets, before=None, after=None)§

Mount the given widgets relative to the app’s screen.

Return type:

AwaitMount

Args:

*widgets: The widget(s) to mount. before: Optional location to mount before. An int is the index

of the child to mount before, a str is a query_one query to find the widget to mount before.

after: Optional location to mount after. An int is the index

of the child to mount after, a str is a query_one query to find the widget to mount after.

Returns:

An awaitable object that waits for widgets to be mounted.

Raises:

MountError: If there is a problem with the mount request.

Note:

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

mount_all(widgets, *, before=None, after=None)§

Mount widgets from an iterable.

Return type:

AwaitMount

Args:

widgets: An iterable of widgets. before: Optional location to mount before. An int is the index

of the child to mount before, a str is a query_one query to find the widget to mount before.

after: Optional location to mount after. An int is the index

of the child to mount after, a str is a query_one query to find the widget to mount after.

Returns:

An awaitable object that waits for widgets to be mounted.

Raises:

MountError: If there is a problem with the mount request.

Note:

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

property name: str | None§

The name of the node.

property namespace_bindings: dict[str, tuple[DOMNode, Binding]]§

Get currently active bindings.

If no widget is focused, then app-level bindings are returned. If a widget is focused, then any bindings present in the active screen and app are merged and returned.

This property may be used to inspect current bindings.

Returns:

A mapping of keys onto pairs of nodes and bindings.

notify(message, *, title='', severity='information', timeout=3)§

Create a notification.

!!! tip :rtype: None

This method is thread-safe.

Args:

message: The message for the notification. title: The title for the notification. severity: The severity of the notification. timeout: The timeout for the notification.

The notify method is used to create an application-wide notification, shown in a [Toast][textual.widgets._toast.Toast], normally originating in the bottom right corner of the display.

Notifications can have the following severity levels:

  • information

  • warning

  • error

The default is information.

Example:

```python # Show an information notification. self.notify(“It’s an older code, sir, but it checks out.”)

# Show a warning. Note that Textual’s notification system allows # for the use of Rich console markup. self.notify(

“Now witness the firepower of this fully ” “[b]ARMED[/b] and [i][b]OPERATIONAL[/b][/i] battle station!”, title=”Possible trap detected”, severity=”warning”,

)

# Show an error. Set a longer timeout so it’s noticed. self.notify(“It’s a trap!”, severity=”error”, timeout=10)

# Show an information notification, but without any sort of title. self.notify(“It’s against my programming to impersonate a deity.”, title=””) ```

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.

Return type:

None

panic(*renderables)§

Exits the app and display error message(s).

Used in response to unexpected errors. For a more graceful exit, see the [exit][textual.app.App.exit] method.

Return type:

None

Args:

*renderables: Text or Rich renderable(s) to display on exit.

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.

pop_screen()§

Pop the current [screen](/guide/screens) from the stack, and switch to the previous screen.

Return type:

Screen[object]

Returns:

The screen that was replaced.

post_display_hook()§

Called immediately after a display is done. Used in tests.

Return type:

None

post_message(message)§

Posts a message on to this widget’s queue.

Return type:

bool

Args:

message: A message (including Event).

Returns:

True if the messages was processed, False if it wasn’t.

prevent(*message_types)§

A context manager to temporarily prevent the given message types from being posted.

Return type:

Generator[None, None, None]

Example:

```python input = self.query_one(Input) with self.prevent(Input.Changed):

input.value = “foo”

```

property pseudo_classes: frozenset[str]§

A (frozen) set of all pseudo classes.

push_screen(screen, callback=None, wait_for_dismiss=False)§

Push a new [screen](/guide/screens) on the screen stack, making it the current screen.

Return type:

AwaitMount | Future[TypeVar(ScreenResultType)]

Args:

screen: A Screen instance or the name of an installed screen. callback: An optional callback function that will be called if the screen is [dismissed][textual.screen.Screen.dismiss] with a result. wait_for_dismiss: If True, awaiting this method will return the dismiss value from the screen. When set to False, awaiting

this method will wait for the screen to be mounted. Note that wait_for_dismiss should only be set to True when running in a worker.

Raises:

NoActiveWorker: If using wait_for_dismiss outside of a worker.

Returns:
An optional awaitable that awaits the mounting of the screen and its children, or an asyncio Future

to await the result of the screen.

query(selector=None)§

Get a DOM query matching a selector.

Return type:

Union[DOMQuery[Widget], DOMQuery[TypeVar(QueryType, bound= Widget)]]

Args:

selector: A CSS selector or None for all nodes.

Returns:

A query object.

query_one(selector, expect_type=None)§

Get a single Widget matching the given selector or selector type.

Return type:

Union[TypeVar(QueryType, bound= Widget), Widget]

Args:

selector: A selector. expect_type: Require the object be of the supplied type, or None for any type.

Raises:

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:

A widget matching the selector.

refresh_css(animate=True)§

Refresh CSS.

Return type:

None

Args:

animate: Also execute CSS animations.

remove_class(*class_names)§

Remove class names from this Node.

Return type:

Self

Args:

*class_names: CSS class names to remove.

Returns:

Self.

remove_mode(mode)§

Removes a mode from the app.

Screens that are running in the stack of that mode are scheduled for pruning.

Return type:

None

Args:

mode: The mode to remove. It can’t be the active mode.

Raises:

ActiveModeError: If trying to remove the active mode. UnknownModeError: If trying to remove an unknown mode.

reset_styles()§

Reset styles back to their initial state.

Return type:

None

property return_code: int | None§

The return code with which the app exited.

Non-zero codes indicate errors. A value of 1 means the app exited with a fatal error. If the app wasn’t exited yet, this will be None.

Example:

The return code can be used to exit the process via sys.exit. `py my_app.run() sys.exit(my_app.return_code) `

property return_value: ReturnType | None§

The return value of the app, or None if it has not yet been set.

The return value is set when calling [exit][textual.app.App.exit].

property rich_style: Style§

Get a Rich Style object for this DOMNode.

Returns:

A Rich style.

run(*, headless=False, size=None, auto_pilot=None)§

Run the app.

Return type:

ReturnType | None

Args:

headless: Run in headless mode (no output). size: Force terminal size to (WIDTH, HEIGHT),

or None to auto-detect.

auto_pilot: An auto pilot coroutine.

Returns:

App return value.

async run_action(action, default_namespace=None)§

Perform an [action](/guide/actions).

Actions are typically associated with key bindings, where you wouldn’t need to call this method manually.

Return type:

bool

Args:

action: Action encoded in a string. default_namespace: Namespace to use if not provided in the action,

or None to use app.

Returns:

True if the event has been handled.

async run_async(*, headless=False, size=None, auto_pilot=None)§

Run the app asynchronously.

Return type:

ReturnType | None

Args:

headless: Run in headless mode (no output). size: Force terminal size to (WIDTH, HEIGHT),

or None to auto-detect.

auto_pilot: An auto pilot coroutine.

Returns:

App return value.

run_test(*, headless=True, size=(80, 24), tooltips=False, notifications=False, message_hook=None)§

An asynchronous context manager for testing apps.

!!! tip :rtype: AsyncGenerator[Pilot[TypeVar(ReturnType)], None]

See the guide for [testing](/guide/testing) Textual apps.

Use this to run your app in “headless” mode (no output) and drive the app via a [Pilot][textual.pilot.Pilot] object.

Example:

```python async with app.run_test() as pilot:

await pilot.click(“#Button.ok”) assert …

```

Args:

headless: Run in headless mode (no output or input). size: Force terminal size to (WIDTH, HEIGHT),

or None to auto-detect.

tooltips: Enable tooltips when testing. notifications: Enable notifications when testing. message_hook: An optional callback that will be called each time any message arrives at any

message pump in the app.

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.

Return type:

Worker[TypeVar(ResultType)]

Args:

work: A function, async function, or an awaitable object to run in a worker. name: A short string to identify the worker (in logs and debugging). group: A short string to identify a group of workers. description: A longer string to store longer information on the worker. exit_on_error: Exit the app if the worker raises an error. Set to False to suppress exceptions. start: Start the worker immediately. exclusive: Cancel all workers in the same group. thread: Mark the worker as a thread worker.

Returns:

New Worker instance.

save_screenshot(filename=None, path='./', time_format=None)§

Save an SVG screenshot of the current screen.

Return type:

str

Args:
filename: Filename of SVG screenshot, or None to auto-generate

a filename with the date and time.

path: Path to directory for output. Defaults to current working directory. time_format: Date and time format to use if filename is None.

Defaults to a format like ISO 8601 with some reserved characters replaced with underscores.

Returns:

Filename of screenshot.

property screen: Screen[object]§

The current active screen.

Returns:

The currently active (visible) screen.

Raises:

ScreenStackError: If there are no screens on the stack.

property screen_stack: Sequence[Screen]§

A snapshot of the current screen stack.

Returns:

A snapshot of the current state of the screen stack.

scroll_sensitivity_x: float§

Number of columns to scroll in the X direction with wheel or trackpad.

scroll_sensitivity_y: float§

Number of lines to scroll in the Y direction with wheel or trackpad.

set_class(add, *class_names)§

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

Return type:

Self

Args:

add: Add the classes if True, otherwise remove them.

Returns:

Self.

set_classes(classes)§

Replace all classes.

Return type:

Self

Args:
classes: A string containing space separated classes, or an

iterable of class names.

Returns:

Self.

set_focus(widget, scroll_visible=True)§

Focus (or unfocus) a widget. A focused widget will receive key events first.

Return type:

None

Args:

widget: Widget to focus. scroll_visible: Scroll widget in to view.

set_interval(interval, callback=None, *, name=None, repeat=0, pause=False)§

Call a function at periodic intervals.

Return type:

Timer

Args:

interval: Time between calls. callback: Function to call. name: Name of the timer object. repeat: Number of times to repeat the call or 0 for continuous. pause: Start the timer paused.

Returns:

A timer object.

set_styles(css=None, **update_styles)§

Set custom styles on this object.

Return type:

Self

Args:

css: Styles in CSS format. **update_styles: Keyword arguments map style names on to style.

Returns:

Self.

set_timer(delay, callback=None, *, name=None, pause=False)§

Make a function call after a delay.

Return type:

Timer

Args:

delay: Time to wait before invoking callback. callback: Callback to call after time has expired. name: Name of the timer (for debug). pause: Start timer paused.

Returns:

A timer object.

property size: Size§

The size of the terminal.

Returns:

Size of the terminal.

async stop_animation(attribute, complete=True)§

Stop an animation on an attribute.

Return type:

None

Args:

attribute: Name of the attribute whose animation should be stopped. complete: Should the animation be set to its final value?

Note:

If there is no animation scheduled or running, this is a no-op.

sub_title: Reactive[str]§

The sub-title for the application.

The initial value for sub_title will be set to the SUB_TITLE class variable if it exists, or an empty string if it doesn’t.

Sub-titles are typically used to show the high-level state of the app, such as the current mode, or path to the file being worked on.

Assign a new value to this attribute to change the sub-title. The new value is always converted to string.

switch_mode(mode)§

Switch to a given mode.

Return type:

AwaitMount

Args:

mode: The mode to switch to.

Returns:
An optionally awaitable object which waits for the screen associated

with the mode to be mounted.

Raises:

UnknownModeError: If trying to switch to an unknown mode.

switch_screen(screen)§

Switch to another [screen](/guide/screens) by replacing the top of the screen stack with a new screen.

Return type:

AwaitMount

Args:

screen: Either a Screen object or screen name (the name argument when installed).

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:

A Rich Style.

title: Reactive[str]§

The title for the application.

The initial value for title will be set to the TITLE class variable if it exists, or the name of the app if it doesn’t.

Assign a new value to this attribute to change the title. The new value is always converted to string.

toggle_class(*class_names)§

Toggle class names on this Node.

Return type:

Self

Args:

*class_names: CSS class names to toggle.

Returns:

Self.

property tree: Tree§

A Rich tree to display the DOM.

Log this to visualize your app in the textual console.

Example:

`python self.log(self.tree) `

Returns:

A Tree renderable.

uninstall_screen(screen)§

Uninstall a screen.

If the screen was not previously installed then this method is a null-op. Uninstalling a screen allows Textual to delete it when it is popped or switched. Note that uninstalling a screen is only required if you have previously installed it with [install_screen][textual.app.App.install_screen]. Textual will also uninstall screens automatically on exit.

Return type:

Optional[str]

Args:

screen: The screen to uninstall or the name of a installed screen.

Returns:

The name of the screen that was uninstalled, or None if no screen was uninstalled.

update_styles(node)§

Immediately update the styles of this node and all descendant nodes.

Should be called whenever CSS classes / pseudo classes change. For example, when you hover over a button, the :hover pseudo class will be added, and this method is called to apply the corresponding :hover styles.

Return type:

None

use_command_palette: bool§

A flag to say if the application should use the command palette.

If set to False any call to [action_command_palette][textual.app.App.action_command_palette] will be ignored.

validate_sub_title(sub_title)§

Make sure the sub-title is set to a string.

Return type:

str

validate_title(title)§

Make sure the title is set to a string.

Return type:

str

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.

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.

Return type:

list[DOMNode] | list[WalkType]

Args:

filter_type: Filter only this type, or None for no filter. with_self: Also yield self in addition to descendants. method: One of “depth” or “breadth”. reverse: Reverse the order (bottom up).

Returns:

A list of nodes.

watch(obj, attribute_name, callback, init=True)§

Watches for modifications to reactive attributes on another object.

Example: :rtype: None

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

```python 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) ```

Args:

obj: Object containing attribute to watch. attribute_name: Attribute to watch. callback: A callback to run when attribute changes. init: Check watchers on first call.

watch_dark(dark)§

Watches the dark bool.

This method handles the transition between light and dark mode when you change the [dark][textual.app.App.dark] attribute.

Return type:

None

property workers: WorkerManager§

The [worker](guide/workers/) manager.

Returns:

An object to manage workers.