hamil_clever_sim.main_display.MainView§
- class MainView(driver_class=None, css_path=None, watch_css=False)[source]§
Bases:
AppCreate 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
An [action](/guide/actions) to add a CSS class to the selected widget.
An [action](/guide/actions) to go back to the previous screen (pop the current screen).
An [action](/guide/actions) to play the terminal 'bell'.
An [action](/guide/actions) to handle a key press using the binding system.
Show the Textual command palette.
An [action](/guide/actions) to focus the given widget.
An [action](/guide/actions) to focus the next widget.
An [action](/guide/actions) to focus the previous widget.
An [action](/guide/actions) to remove the topmost screen and makes the new topmost screen active.
An [action](/guide/actions) to push a new screen on to the stack and make it active.
An [action](/guide/actions) to quit the app as soon as possible.
An [action](/guide/actions) to remove a CSS class from the selected widget.
This [action](/guide/actions) will save an SVG file containing the current contents of the screen.
An [action](/guide/actions) that switches to the given mode..
An [action](/guide/actions) to switch screens.
An [action](/guide/actions) to toggle a CSS class on the selected widget.
An [action](/guide/actions) to toggle dark mode.
Add class names to this Node.
Adds a mode and its corresponding base screen to the app.
Animate an attribute.
A context manager to suspend all repaints until the end of the batch.
Capture content that is printed (or written to stdout / stderr).
Play the console 'bell'.
Bind a key to an action.
Schedule a callback to run after all messages are processed and the screen has been refreshed.
Run a callable from another thread, and return the result.
Schedule a callback to run after all messages are processed in this object.
Schedule a callback to run immediately after processing the current message.
Send all mouse events to the given widget or disable mouse capture.
Handle a key press.
Prompt the message pump to call idle if the queue is empty.
Check if a given message is enabled (allowed to be sent).
Clear all the current notifications.
compose- rtype:
Iterable[Widget]
Add a node to children.
Disable message types from being processed.
Dispatch a key event to method.
Enable processing of messages types.
End capturing of prints.
Exit the app, and return the supplied result.
Export an SVG screenshot of the current screen.
Get the first child (immediate descendent) of this DOMNode with the given ID.
Get a child of a give type.
Get a "component" styles object (must be defined in COMPONENT_CLASSES classvar).
Get a mapping of variables used to pre-populate CSS.
Get a driver class for this platform.
For a given key, return how it should be displayed in an app (e.g. in the Footer widget).
Get any pseudo classes applicable to this Node, e.g. hover, focus.
Get an installed screen.
Get the widget under the given coordinates.
Get the first descendant widget with the given ID.
handle_simulation_run- rtype:
None
handle_tab_active- rtype:
None
Check if the Node has all the given class names.
Check for pseudo classes (such as hover, focus etc)
Install a screen.
Check if a widget is mounted.
Check if a given screen has been installed.
Mount the given widgets relative to the app's screen.
Mount widgets from an iterable.
Create a notification.
Called after styles are updated.
on_callback- rtype:
None
on_event- rtype:
None
on_timer- rtype:
None
Exits the app and display error message(s).
Pop the current [screen](/guide/screens) from the stack, and switch to the previous screen.
Called immediately after a display is done.
Posts a message on to this widget's queue.
A context manager to temporarily prevent the given message types from being posted.
Push a new [screen](/guide/screens) on the screen stack, making it the current screen.
Get a DOM query matching a selector.
Get a single Widget matching the given selector or selector type.
refresh- rtype:
None
Refresh CSS.
Remove class names from this Node.
Removes a mode from the app.
render- rtype:
Union[ConsoleRenderable,RichCast,str]
Reset styles back to their initial state.
Run the app.
Perform an [action](/guide/actions).
Run the app asynchronously.
An asynchronous context manager for testing apps.
Run work in a worker.
Save an SVG screenshot of the current screen.
Add or remove class(es) based on a condition.
Replace all classes.
Focus (or unfocus) a widget.
Call a function at periodic intervals.
Set custom styles on this object.
Make a function call after a delay.
Stop an animation on an attribute.
Switch to a given mode.
Switch to another [screen](/guide/screens) by replacing the top of the screen stack with a new screen.
Toggle class names on this Node.
Uninstall a screen.
Immediately update the styles of this node and all descendant nodes.
Make sure the sub-title is set to a string.
Make sure the title is set to a string.
Walk the subtree rooted at this node, and return every descendant encountered in a list.
Watches for modifications to reactive attributes on another object.
Watches the dark bool.
Attributes
AUTO_FOCUSA selector to determine what to focus automatically when a screen is activated.
BINDINGSCOMMANDSCommand providers used by the [command palette](/guide/command_palette).
COMPONENT_CLASSESCSSInline CSS, useful for quick scripts.
CSS_PATHFile paths to load CSS from.
DEFAULT_CLASSESDEFAULT_CSSENABLE_COMMAND_PALETTEShould the [command palette][textual.command.CommandPalette] be enabled for the application?
ExpectTypeMODESModes associated with the app and their base screens.
SCOPED_CSSShould default css be limited to the widget type?
SCREENSScreens associated with the app for the lifetime of the app.
SUB_TITLEA class variable to set the default sub-title for the application.
TITLEA class variable to set the default title for the application.
WalkTypeA list of ancestor nodes found by tracing a path all the way back to App.
A list of ancestor nodes found by tracing a path all the way back to App.
animatorGet the current app.
Number of seconds between automatic refresh, or None for no automatic refresh.
The background color and the color of the parent's background.
A view onto the app's immediate children.
The widget's background and foreground colors, and the parent's background and foreground colors.
A CSS selector that identifies this DOM node.
A syntax highlighted CSS identifier.
A list of nodes from the App to this node, forming a "path".
A Rich tree to display the DOM, annotated with the node's CSS.
The name of the currently active mode.
Is debug mode enabled?
Should the DOM node be displayed?
The child nodes which will be displayed.
The widget that is focused on the currently active screen, or None.
Does this object have a parent?
The ID of this node, or None if the node has no ID.
Is the node attached to the app via the DOM?
Is the driver running in 'headless' mode?
Is the node a modal?
Is the parent active?
Is the message pump running (potentially processing messages)?
The textual logger.
The name of the node.
Get currently active bindings.
The parent node.
A (frozen) set of all pseudo classes.
The return code with which the app exited.
The return value of the app, or None if it has not yet been set.
Get a Rich Style object for this DOMNode.
The current active screen.
A snapshot of the current screen stack.
The size of the terminal.
taskGet the text style object.
A Rich tree to display the DOM.
Is this widget visible in the DOM?
The [worker](guide/workers/) manager.
The title for the application.
The sub-title for the application.
Use a dark theme if True, otherwise use a light theme.
The position of the terminal cursor in screen-space.
A flag to say if the application should use the command palette.
Number of columns to scroll in the X direction with wheel or trackpad.
Number of lines to scroll in the Y direction with wheel or trackpad.
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.
- 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
- call_next(callback, *args, **kwargs)§
Schedule a callback to run immediately after processing the current message.
- Return type:
None
- 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:
Trueif the node has all the given class names, otherwiseFalse.
- 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
beforeoraftercan be provided. If both are provided aMountErrorwill 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
beforeoraftercan be provided. If both are provided aMountErrorwill 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:
NoneThis 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]
- 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:
- 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:
NoneHere’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.