textual.app
Here you will find the App class, which is the base class for Textual apps.
See app basics for how to build Textual apps.
AutopilotCallbackType
module-attribute
¶
Signature for valid callbacks that can be used to control apps.
App
¶
App(driver_class=None, css_path=None, watch_css=False)
Bases: Generic[ReturnType]
, DOMNode
The base class for Textual Applications.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Type[Driver] | None
|
Driver class or |
None
|
|
CSSPathType | None
|
Path to CSS or |
None
|
|
bool
|
Reload CSS if the files changed. This is set automatically if
you are using |
False
|
Raises:
Type | Description |
---|---|
CssPathError
|
When the supplied CSS path(s) are an unexpected type. |
AUTO_FOCUS
class-attribute
¶
A selector to determine what to focus automatically when a screen is activated.
The widget focused is the first that matches the given CSS selector.
Setting to None
or ""
disables auto focus.
CLOSE_TIMEOUT
class-attribute
instance-attribute
¶
Timeout waiting for widget's to close, or None
for no timeout.
COMMANDS
class-attribute
¶
COMMANDS = {get_system_commands}
Command providers used by the command palette.
Should be a set of command.Provider classes.
CSS
class-attribute
¶
Inline CSS, useful for quick scripts. This is loaded after CSS_PATH, and therefore takes priority in the event of a specificity clash.
ENABLE_COMMAND_PALETTE
class-attribute
¶
Should the command palette be enabled for the application?
MODES
class-attribute
¶
NOTIFICATION_TIMEOUT
class-attribute
¶
Default number of seconds to show notifications before removing them.
SUB_TITLE
class-attribute
instance-attribute
¶
A class variable to set the default sub-title for the application.
To update the sub-title while the app is running, you can set the sub_title attribute.
See also the Screen.SUB_TITLE
attribute.
TITLE
class-attribute
instance-attribute
¶
A class variable to set the default title for the application.
To update the title while the app is running, you can set the title attribute.
See also the Screen.TITLE
attribute.
active_bindings
property
¶
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:
Type | Description |
---|---|
dict[str, ActiveBinding]
|
Active binding information |
animation_level
instance-attribute
¶
animation_level = TEXTUAL_ANIMATIONS
Determines what type of animations the app will display.
ansi_theme
property
¶
The ANSI TerminalTheme currently being used.
Defines how colors defined as ANSI (e.g. magenta
) inside Rich renderables
are mapped to hex codes.
ansi_theme_dark
class-attribute
instance-attribute
¶
Maps ANSI colors to hex colors using a Rich TerminalTheme object while in dark mode.
ansi_theme_light
class-attribute
instance-attribute
¶
Maps ANSI colors to hex colors using a Rich TerminalTheme object while in light mode.
app_focus
class-attribute
instance-attribute
¶
Indicates if the app has focus.
When run in the terminal, the app always has focus. When run in the web, the app will get focus when the terminal widget has focus.
app_resume_signal
instance-attribute
¶
app_resume_signal = Signal(self, 'app-resume')
The signal that is published when the app is resumed after a suspend.
When the app is resumed after a
App.suspend
call this signal will be
published;
subscribe to this signal to
perform work after the app has resumed.
app_suspend_signal
instance-attribute
¶
app_suspend_signal = Signal(self, 'app-suspend')
The signal that is published when the app is suspended.
When App.suspend
is called this signal
will be published;
subscribe to this signal to
perform work before the suspension takes place.
children
property
¶
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:
Type | Description |
---|---|
Sequence['Widget']
|
A sequence of widgets. |
cursor_position
instance-attribute
¶
cursor_position = Offset(0, 0)
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
class-attribute
instance-attribute
¶
focused
property
¶
The widget that is focused on the currently active screen, or None
.
Focused widgets receive keyboard input.
Returns:
Type | Description |
---|---|
Widget | None
|
The currently focused widget, or |
is_headless
property
¶
Is the app running in 'headless' mode?
Headless mode is used when running tests with run_test.
return_code
property
¶
return_value
property
¶
The return value of the app, or None
if it has not yet been set.
The return value is set when calling exit.
screen
property
¶
The current active screen.
Returns:
Type | Description |
---|---|
Screen[object]
|
The currently active (visible) screen. |
Raises:
Type | Description |
---|---|
ScreenStackError
|
If there are no screens on the stack. |
screen_stack
property
¶
scroll_sensitivity_x
instance-attribute
¶
Number of columns to scroll in the X direction with wheel or trackpad.
scroll_sensitivity_y
instance-attribute
¶
Number of lines to scroll in the Y direction with wheel or trackpad.
sub_title
class-attribute
instance-attribute
¶
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.
title
class-attribute
instance-attribute
¶
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.
use_command_palette
instance-attribute
¶
A flag to say if the application should use the command palette.
If set to False
any call to
action_command_palette
will be ignored.
workers
property
¶
action_add_class
async
¶
action_add_class(selector, class_name)
action_back
async
¶
An action to go back to the previous screen (pop the current screen).
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.)
action_pop_screen
async
¶
An action to remove the topmost screen and makes the new topmost screen active.
action_remove_class
async
¶
action_remove_class(selector, class_name)
action_screenshot
¶
action_suspend_process
¶
Suspend the process into the background.
Note
On Unix and Unix-like systems a SIGTSTP
is sent to the
application's process. Currently on Windows and when running
under Textual Web this is a non-operation.
action_toggle_class
async
¶
action_toggle_class(selector, class_name)
add_mode
¶
add_mode(mode, base_screen)
Adds a mode and its corresponding base screen to the app.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str
|
The new mode. |
required |
|
str | Screen | Callable[[], Screen]
|
The base screen associated with the given mode. |
required |
Raises:
Type | Description |
---|---|
InvalidModeError
|
If the name of the mode is not valid/duplicated. |
animate
¶
animate(
attribute,
value,
*,
final_value=...,
duration=None,
speed=None,
delay=0.0,
easing=DEFAULT_EASING,
on_complete=None,
level="full"
)
Animate an attribute.
See the guide for how to use the animation system.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str
|
Name of the attribute to animate. |
required |
|
float | Animatable
|
The value to animate to. |
required |
|
object
|
The final value of the animation. |
...
|
|
float | None
|
The duration (in seconds) of the animation. |
None
|
|
float | None
|
The speed of the animation. |
None
|
|
float
|
A delay (in seconds) before the animation starts. |
0.0
|
|
EasingFunction | str
|
An easing method. |
DEFAULT_EASING
|
|
CallbackType | None
|
A callable to invoke when the animation is finished. |
None
|
|
AnimationLevel
|
Minimum level required for the animation to take place (inclusive). |
'full'
|
begin_capture_print
¶
Capture content that is printed (or written to stdout / stderr).
If printing is captured, the target
will be sent an events.Print message.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
MessageTarget
|
The widget where print content will be sent. |
required |
|
bool
|
Capture stdout. |
True
|
|
bool
|
Capture stderr. |
True
|
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.
bind
¶
bind(
keys,
action,
*,
description="",
show=True,
key_display=None
)
Bind a key to an action.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str
|
A comma separated list of keys, i.e. |
required |
|
str
|
Action to bind to. |
required |
|
str
|
Short description of action. |
''
|
|
bool
|
Show key in UI. |
True
|
|
str | None
|
Replacement text for key, or None to use default. |
None
|
call_from_thread
¶
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
Consider using post_message which is also thread-safe.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Callable[..., CallThreadReturnType | Awaitable[CallThreadReturnType]]
|
A callable to run. |
required |
|
Any
|
Arguments to the callback. |
()
|
|
Any
|
Keyword arguments for the callback. |
{}
|
Raises:
Type | Description |
---|---|
RuntimeError
|
If the app isn't running or if this method is called from the same thread where the app is running. |
Returns:
Type | Description |
---|---|
CallThreadReturnType
|
The result of the callback. |
compose
¶
Yield child widgets for a container.
This method should be implemented in a subclass.
end_capture_print
¶
end_capture_print(target)
End capturing of prints.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
MessageTarget
|
The widget that was capturing prints. |
required |
exit
¶
exit(result=None, return_code=0, message=None)
Exit the app, and return the supplied result.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
ReturnType | None
|
Return value. |
None
|
|
int
|
The return code. Use non-zero values for error codes. |
0
|
|
RenderableType | None
|
Optional message to display on exit. |
None
|
export_screenshot
¶
export_screenshot(*, title=None)
Export an SVG screenshot of the current screen.
See also save_screenshot which writes the screenshot to a file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str | None
|
The title of the exported screenshot or None to use app title. |
None
|
get_child_by_id
¶
get_child_by_id(
id: str, expect_type: type[ExpectType]
) -> ExpectType
get_child_by_id(id, expect_type=None)
Get the first child (immediate descendant) of this DOMNode with the given ID.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str
|
The ID of the node to search for. |
required |
|
type[ExpectType] | None
|
Require the object be of the supplied type,
or use |
None
|
Returns:
Type | Description |
---|---|
ExpectType | Widget
|
The first child of this node with the specified ID. |
Raises:
Type | Description |
---|---|
NoMatches
|
If no children could be found for this ID. |
WrongType
|
If the wrong type was found. |
get_child_by_type
¶
get_child_by_type(expect_type)
get_css_variables
¶
get_default_screen
¶
Get the default screen.
This is called when the App is first composed. The returned screen instance will be the first screen on the stack.
Implement this method if you would like to use a custom Screen as the default screen.
Returns:
Type | Description |
---|---|
Screen
|
A screen instance. |
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.
Returns:
Type | Description |
---|---|
Type[Driver]
|
A Driver class which manages input and display. |
get_key_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.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str
|
The binding key string. |
required |
Returns:
Type | Description |
---|---|
str
|
The display string for the input key. |
get_loading_widget
¶
Get a widget to be used as a loading indicator.
Extend this method if you want to display the loading state a little differently.
Returns:
Type | Description |
---|---|
Widget
|
A widget to display a loading state. |
get_widget_at
¶
get_widget_by_id
¶
get_widget_by_id(
id: str, expect_type: type[ExpectType]
) -> ExpectType
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
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str
|
The ID to search for in the subtree |
required |
|
type[ExpectType] | None
|
Require the object be of the supplied type, or None for any type. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
ExpectType | Widget
|
The first descendant encountered with this ID. |
Raises:
Type | Description |
---|---|
NoMatches
|
if no children could be found for this ID |
WrongType
|
if the wrong type was found. |
install_screen
¶
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 or switch_screen to make a new screen current.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Screen
|
Screen to install. |
required |
|
str
|
Unique name to identify the screen. |
required |
Raises:
Type | Description |
---|---|
ScreenError
|
If the screen can't be installed. |
Returns:
Type | Description |
---|---|
None
|
An awaitable that awaits the mounting of the screen and its children. |
mount
¶
Mount the given widgets relative to the app's screen.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Widget
|
The widget(s) to mount. |
()
|
|
int | str | Widget | None
|
Optional location to mount before. An |
None
|
|
int | str | Widget | None
|
Optional location to mount after. An |
None
|
Returns:
Type | Description |
---|---|
AwaitMount
|
An awaitable object that waits for widgets to be mounted. |
Raises:
Type | Description |
---|---|
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
¶
Mount widgets from an iterable.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Iterable[Widget]
|
An iterable of widgets. |
required |
|
int | str | Widget | None
|
Optional location to mount before. An |
None
|
|
int | str | Widget | None
|
Optional location to mount after. An |
None
|
Returns:
Type | Description |
---|---|
AwaitMount
|
An awaitable object that waits for widgets to be mounted. |
Raises:
Type | Description |
---|---|
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.
notify
¶
Create a notification.
Tip
This method is thread-safe.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str
|
The message for the notification. |
required |
|
str
|
The title for the notification. |
''
|
|
SeverityLevel
|
The severity of the notification. |
'information'
|
|
float | None
|
The timeout (in seconds) for the notification, or |
None
|
The notify
method is used to create an application-wide
notification, shown in a 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
# 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="")
panic
¶
panic(*renderables)
Exits the app and display error message(s).
Used in response to unexpected errors. For a more graceful exit, see the exit method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
RenderableType
|
Text or Rich renderable(s) to display on exit. |
()
|
pop_screen
¶
Pop the current screen from the stack, and switch to the previous screen.
Returns:
Type | Description |
---|---|
AwaitComplete
|
The screen that was replaced. |
push_screen
¶
push_screen(
screen: Screen[ScreenResultType] | str,
callback: (
ScreenResultCallbackType[ScreenResultType] | None
) = None,
wait_for_dismiss: Literal[False] = False,
) -> AwaitMount
push_screen(
screen: Screen[ScreenResultType] | str,
callback: (
ScreenResultCallbackType[ScreenResultType] | None
) = None,
wait_for_dismiss: Literal[True] = True,
) -> Future[ScreenResultType]
push_screen(screen, callback=None, wait_for_dismiss=False)
Push a new screen on the screen stack, making it the current screen.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Screen[ScreenResultType] | str
|
A Screen instance or the name of an installed screen. |
required |
|
ScreenResultCallbackType[ScreenResultType] | None
|
An optional callback function that will be called if the screen is dismissed with a result. |
None
|
|
bool
|
If |
False
|
Raises:
Type | Description |
---|---|
NoActiveWorker
|
If using |
Returns:
Type | Description |
---|---|
AwaitMount | Future[ScreenResultType]
|
An optional awaitable that awaits the mounting of the screen and its children, or an asyncio Future to await the result of the screen. |
push_screen_wait
async
¶
push_screen_wait(
screen: Screen[ScreenResultType],
) -> ScreenResultType
push_screen_wait(screen)
Push a screen and wait for the result (received from Screen.dismiss
).
Note that this method may only be called when running in a worker.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Screen[ScreenResultType] | str
|
A screen or the name of an installed screen. |
required |
Returns:
Type | Description |
---|---|
ScreenResultType | Any
|
The screen's result. |
recompose
async
¶
Recompose the widget.
Recomposing will remove children and call self.compose
again to remount.
refresh
¶
Refresh the entire screen.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
bool
|
Repaint the widget (will call render() again). |
True
|
|
bool
|
Also layout widgets in the view. |
False
|
|
bool
|
Re-compose the widget (will remove and re-mount children). |
False
|
Returns:
Type | Description |
---|---|
Self
|
The |
remove_mode
¶
remove_mode(mode)
Removes a mode from the app.
Screens that are running in the stack of that mode are scheduled for pruning.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str
|
The mode to remove. It can't be the active mode. |
required |
Raises:
Type | Description |
---|---|
ActiveModeError
|
If trying to remove the active mode. |
UnknownModeError
|
If trying to remove an unknown mode. |
render
¶
Render method, inherited from widget, to render the screen's background.
May be overridden to customize background visuals.
run
¶
run(
*,
headless=False,
inline=False,
inline_no_clear=False,
mouse=True,
size=None,
auto_pilot=None
)
Run the app.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
bool
|
Run in headless mode (no output). |
False
|
|
bool
|
Run the app inline (under the prompt). |
False
|
|
bool
|
Don't clear the app output when exiting an inline app. |
False
|
|
bool
|
Enable mouse support. |
True
|
|
tuple[int, int] | None
|
Force terminal size to |
None
|
|
AutopilotCallbackType | None
|
An auto pilot coroutine. |
None
|
Returns:
Type | Description |
---|---|
ReturnType | None
|
App return value. |
run_action
async
¶
run_action(action, default_namespace=None)
Perform an action.
Actions are typically associated with key bindings, where you wouldn't need to call this method manually.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str | ActionParseResult
|
Action encoded in a string. |
required |
|
DOMNode | None
|
Namespace to use if not provided in the action, or None to use app. |
None
|
Returns:
Type | Description |
---|---|
bool
|
True if the event has been handled. |
run_async
async
¶
run_async(
*,
headless=False,
inline=False,
inline_no_clear=False,
mouse=True,
size=None,
auto_pilot=None
)
Run the app asynchronously.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
bool
|
Run in headless mode (no output). |
False
|
|
bool
|
Run the app inline (under the prompt). |
False
|
|
bool
|
Don't clear the app output when exiting an inline app. |
False
|
|
bool
|
Enable mouse support. |
True
|
|
tuple[int, int] | None
|
Force terminal size to |
None
|
|
AutopilotCallbackType | None
|
An autopilot coroutine. |
None
|
Returns:
Type | Description |
---|---|
ReturnType | None
|
App return value. |
run_test
async
¶
run_test(
*,
headless=True,
size=(80, 24),
tooltips=False,
notifications=False,
message_hook=None
)
An asynchronous context manager for testing apps.
Tip
See the guide for testing Textual apps.
Use this to run your app in "headless" mode (no output) and drive the app via a Pilot object.
Example:
```python
async with app.run_test() as pilot:
await pilot.click("#Button.ok")
assert ...
```
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
bool
|
Run in headless mode (no output or input). |
True
|
|
tuple[int, int] | None
|
Force terminal size to |
(80, 24)
|
|
bool
|
Enable tooltips when testing. |
False
|
|
bool
|
Enable notifications when testing. |
False
|
|
Callable[[Message], None] | None
|
An optional callback that will be called each time any message arrives at any message pump in the app. |
None
|
save_screenshot
¶
save_screenshot(filename=None, path=None, time_format=None)
Save an SVG screenshot of the current screen.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str | None
|
Filename of SVG screenshot, or None to auto-generate a filename with the date and time. |
None
|
|
str | None
|
Path to directory for output. Defaults to current working directory. |
None
|
|
str | None
|
Date and time format to use if filename is None. Defaults to a format like ISO 8601 with some reserved characters replaced with underscores. |
None
|
Returns:
Type | Description |
---|---|
str
|
Filename of screenshot. |
set_focus
¶
set_focus(widget, scroll_visible=True)
stop_animation
async
¶
suspend
¶
A context manager that temporarily suspends the app.
While inside the with
block, the app will stop reading input and
emitting output. Other applications will have full control of the
terminal, configured as it was before the app started running. When
the with
block ends, the application will start reading input and
emitting output again.
Raises:
Type | Description |
---|---|
SuspendNotSupported
|
If the environment doesn't support suspending. |
Note
Suspending the application is currently only supported on Unix-like operating systems and Microsoft Windows. Suspending is not supported in Textual Web.
switch_mode
¶
switch_mode(mode)
Switch to a given mode.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
str
|
The mode to switch to. |
required |
Returns:
Type | Description |
---|---|
AwaitMount
|
An optionally awaitable object which waits for the screen associated with the mode to be mounted. |
Raises:
Type | Description |
---|---|
UnknownModeError
|
If trying to switch to an unknown mode. |
uninstall_screen
¶
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 will also uninstall screens automatically on exit.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
|
Screen | str
|
The screen to uninstall or the name of an installed screen. |
required |
Returns:
Type | Description |
---|---|
str | None
|
The name of the screen that was uninstalled, or None if no screen was uninstalled. |
update_styles
¶
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.
ScreenStackError
¶
Bases: ScreenError
Raised when trying to manipulate the screen stack incorrectly.
SuspendNotSupported
¶
Bases: Exception
Raised if suspending the application is not supported.
This exception is raised if App.suspend
is called while
the application is running in an environment where this isn't supported.
get_system_commands
¶
Callable to lazy load the system commands.
Returns:
Type | Description |
---|---|
type[SystemCommands]
|
System commands class. |