Skip to content

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

AutopilotCallbackType = (
    "Callable[[Pilot[object]], Coroutine[Any, Any, None]]"
)

Signature for valid callbacks that can be used to control apps.

CommandCallback module-attribute

CommandCallback = (
    "Callable[[], Awaitable[Any]] | Callable[[], Any]"
)

Signature for callbacks used in get_system_commands

RenderResult module-attribute

RenderResult = (
    "RenderableType | Visual | SupportsTextualize"
)

Result of Widget.render()

ScreenType module-attribute

ScreenType = TypeVar('ScreenType', bound=Screen)

Type var for a Screen, used in get_screen.

ActionError

Bases: Exception

Base class for exceptions relating to actions.

ActiveModeError

Bases: ModeError

Raised when attempting to remove the currently active mode.

App

App(
    driver_class=None,
    css_path=None,
    watch_css=False,
    ansi_color=False,
)

Bases: Generic[ReturnType], DOMNode

The base class for Textual Applications.

Parameters:

Name Type Description Default

driver_class

Type[Driver] | None

Driver class or None to auto-detect. This will be used by some Textual tools.

None

css_path

CSSPathType | None

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.

None

watch_css

bool

Reload CSS if the files changed. This is set automatically if you are using textual run with the dev switch.

False

ansi_color

bool

Allow ANSI colors if True, or convert ANSI colors to to RGB if False.

False

Raises:

Type Description
CssPathError

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

ALLOW_IN_MAXIMIZED_VIEW class-attribute

ALLOW_IN_MAXIMIZED_VIEW = 'Footer'

The default value of Screen.ALLOW_IN_MAXIMIZED_VIEW.

AUTO_FOCUS class-attribute

AUTO_FOCUS = '*'

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.

BINDINGS class-attribute

BINDINGS = [
    Binding(
        "ctrl+c", "quit", "Quit", show=False, priority=True
    )
]

The default key bindings.

BINDING_GROUP_TITLE class-attribute instance-attribute

BINDING_GROUP_TITLE = None

Set to text to show in the key panel.

CLOSE_TIMEOUT class-attribute instance-attribute

CLOSE_TIMEOUT = 5.0

Timeout waiting for widget's to close, or None for no timeout.

COMMANDS class-attribute

Command providers used by the command palette.

Should be a set of command.Provider classes.

COMMAND_PALETTE_BINDING class-attribute

COMMAND_PALETTE_BINDING = 'ctrl+p'

The key that launches the command palette (if enabled by App.ENABLE_COMMAND_PALETTE).

COMMAND_PALETTE_DISPLAY class-attribute

COMMAND_PALETTE_DISPLAY = None

How the command palette key should be displayed in the footer (or None for default).

CSS class-attribute

CSS = ''

Inline CSS, useful for quick scripts. This is loaded after CSS_PATH, and therefore takes priority in the event of a specificity clash.

CSS_PATH class-attribute

CSS_PATH = None

File paths to load CSS from.

DEFAULT_MODE class-attribute

DEFAULT_MODE = '_default'

Name of the default mode.

ENABLE_COMMAND_PALETTE class-attribute

ENABLE_COMMAND_PALETTE = True

Should the command palette be enabled for the application?

ESCAPE_TO_MINIMIZE class-attribute

ESCAPE_TO_MINIMIZE = True

Use escape key to minimize widgets (potentially overriding bindings).

This is the default value, used if the active screen's ESCAPE_TO_MINIMIZE is not changed from None.

INLINE_PADDING class-attribute

INLINE_PADDING = 1

Number of blank lines above an inline app.

MODES class-attribute

MODES = {}

Modes associated with the app and their base screens.

The base screen is the screen at the bottom of the mode stack. You can think of it as the default screen for that stack. The base screens can be names of screens listed in SCREENS, Screen instances, or callables that return screens.

Example
class HelpScreen(Screen[None]):
    ...

class MainAppScreen(Screen[None]):
    ...

class MyApp(App[None]):
    MODES = {
        "default": "main",
        "help": HelpScreen,
    }

    SCREENS = {
        "main": MainAppScreen,
    }

    ...

NOTIFICATION_TIMEOUT class-attribute

NOTIFICATION_TIMEOUT = 5

Default number of seconds to show notifications before removing them.

SCREENS class-attribute

SCREENS = {}

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

SUB_TITLE class-attribute instance-attribute

SUB_TITLE = None

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.

SUSPENDED_SCREEN_CLASS class-attribute

SUSPENDED_SCREEN_CLASS = ''

Class to apply to suspended screens, or empty string for no class.

TITLE class-attribute instance-attribute

TITLE = None

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.

TOOLTIP_DELAY class-attribute instance-attribute

TOOLTIP_DELAY = 0.5

The time in seconds after which a tooltip gets displayed.

active_bindings property

active_bindings

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]

A dict that maps keys on to binding information.

animation_level instance-attribute

animation_level = TEXTUAL_ANIMATIONS

Determines what type of animations the app will display.

See textual.constants.TEXTUAL_ANIMATIONS.

animator property

animator

The animator object.

ansi_color class-attribute instance-attribute

ansi_color = Reactive(False)

Allow ANSI colors in UI?

ansi_theme property

ansi_theme

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

ansi_theme_dark = Reactive(MONOKAI, init=False)

Maps ANSI colors to hex colors using a Rich TerminalTheme object while using a dark theme.

ansi_theme_light class-attribute instance-attribute

ansi_theme_light = Reactive(ALABASTER, init=False)

Maps ANSI colors to hex colors using a Rich TerminalTheme object while using a light theme.

app_focus class-attribute instance-attribute

app_focus = Reactive(True, compute=False)

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.

available_themes property

available_themes

All available themes (all built-in themes plus any that have been registered).

A dictionary mapping theme names to Theme instances.

children property

children

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.

current_mode property

current_mode

The name of the currently active mode.

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.

debug property

debug

Is debug mode enabled?

escape_to_minimize property

escape_to_minimize

Use the escape key to minimize?

When a widget is maximized, this boolean determines if the escape key will minimize the widget (potentially overriding any bindings).

The default logic is to use the screen's ESCAPE_TO_MINIMIZE classvar if it is set to True or False. If the classvar on the screen is not set (and left as None), then the app's ESCAPE_TO_MINIMIZE is used.

focused property

focused

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 None if nothing is focused.

is_attached property

is_attached

Is this node linked to the app through the DOM?

is_dom_root property

is_dom_root

Is this a root node (i.e. the App)?

is_headless property

is_headless

Is the app running in 'headless' mode?

Headless mode is used when running tests with run_test.

is_inline property

is_inline

Is the app running in 'inline' mode?

is_web property

is_web

Is the app running in 'web' mode via a browser?

log property

log

The textual logger.

Example
self.log("Hello, World!")
self.log(self.tree)

Returns:

Type Description
Logger

A Textual logger.

return_code property

return_code

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 hasn't exited yet, this will be None.

Example

The return code can be used to exit the process via sys.exit.

my_app.run()
sys.exit(my_app.return_code)

return_value property

return_value

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

screen

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

screen_stack

A snapshot of the current screen stack.

Returns:

Type Description
list[Screen[Any]]

A snapshot of the current state of the screen stack.

scroll_sensitivity_x instance-attribute

scroll_sensitivity_x = 4.0

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

scroll_sensitivity_y instance-attribute

scroll_sensitivity_y = 2.0

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

size property

size

The size of the terminal.

Returns:

Type Description
Size

Size of the terminal.

sub_title class-attribute instance-attribute

sub_title = SUB_TITLE if SUB_TITLE is not None else ''

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.

theme class-attribute instance-attribute

The name of the currently active theme.

theme_changed_signal instance-attribute

theme_changed_signal = Signal(self, 'theme-changed')

Signal that is published when the App's theme is changed.

Subscribers will receive the new theme object as an argument to the callback.

theme_variables instance-attribute

theme_variables = {}

Variables generated from the current theme.

title class-attribute instance-attribute

title = TITLE if TITLE is not None else f'{__name__}'

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

use_command_palette = ENABLE_COMMAND_PALETTE

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

workers

The worker manager.

Returns:

Type Description
WorkerManager

An object to manage workers.

action_add_class async

action_add_class(selector, class_name)

An action to add a CSS class to the selected widget.

Parameters:

Name Type Description Default

selector

str

Selects the widget to add the class to.

required

class_name

str

The class to add to the selected widget.

required

action_back async

action_back()

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_bell async

action_bell()

An action to play the terminal 'bell'.

action_change_theme

action_change_theme()

An action to change the current theme.

action_command_palette

action_command_palette()

Show the Textual command palette.

action_focus async

action_focus(widget_id)

An action to focus the given widget.

Parameters:

Name Type Description Default

widget_id

str

ID of widget to focus.

required

action_focus_next

action_focus_next()

An action to focus the next widget.

action_focus_previous

action_focus_previous()

An action to focus the previous widget.

action_hide_help_panel

action_hide_help_panel()

Hide the keys panel (if present).

action_pop_screen async

action_pop_screen()

An action to remove the topmost screen and makes the new topmost screen active.

action_push_screen async

action_push_screen(screen)

An action to push a new screen on to the stack and make it active.

Parameters:

Name Type Description Default

screen

str

Name of the screen.

required

action_quit async

action_quit()

An action to quit the app as soon as possible.

action_remove_class async

action_remove_class(selector, class_name)

An action to remove a CSS class from the selected widget.

Parameters:

Name Type Description Default

selector

str

Selects the widget to remove the class from.

required

class_name

str

The class to remove from the selected widget.

required

action_screenshot

action_screenshot(filename=None, path=None)

This action will save an SVG file containing the current contents of the screen.

Parameters:

Name Type Description Default

filename

str | None

Filename of screenshot, or None to auto-generate.

None

path

str | None

Path to directory. Defaults to the user's Downloads directory.

None

action_show_help_panel

action_show_help_panel()

Show the keys panel.

action_simulate_key async

action_simulate_key(key)

An action to simulate a key press.

This will invoke the same actions as if the user had pressed the key.

Parameters:

Name Type Description Default

key

str

The key to process.

required

action_suspend_process

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_switch_mode async

action_switch_mode(mode)

An action that switches to the given mode.

action_switch_screen async

action_switch_screen(screen)

An action to switch screens.

Parameters:

Name Type Description Default

screen

str

Name of the screen.

required

action_toggle_class async

action_toggle_class(selector, class_name)

An action to toggle a CSS class on the selected widget.

Parameters:

Name Type Description Default

selector

str

Selects the widget to toggle the class on.

required

class_name

str

The class to toggle on the selected widget.

required

action_toggle_dark

action_toggle_dark()

An action to toggle the theme between textual-light and textual-dark. This is offered as a convenience to simplify backwards compatibility with previous versions of Textual which only had light mode and dark mode.

add_mode

add_mode(mode, base_screen)

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

Parameters:

Name Type Description Default

mode

str

The new mode.

required

base_screen

str | 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

attribute

str

Name of the attribute to animate.

required

value

float | Animatable

The value to animate to.

required

final_value

object

The final value of the animation.

...

duration

float | None

The duration (in seconds) of the animation.

None

speed

float | None

The speed of the animation.

None

delay

float

A delay (in seconds) before the animation starts.

0.0

easing

EasingFunction | str

An easing method.

DEFAULT_EASING

on_complete

CallbackType | None

A callable to invoke when the animation is finished.

None

level

AnimationLevel

Minimum level required for the animation to take place (inclusive).

'full'

batch_update

batch_update()

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

begin_capture_print

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 message.

Parameters:

Name Type Description Default

target

MessageTarget

The widget where print content will be sent.

required

stdout

bool

Capture stdout.

True

stderr

bool

Capture stderr.

True

bell

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

keys

str

A comma separated list of keys, i.e.

required

action

str

Action to bind to.

required

description

str

Short description of action.

''

show

bool

Show key in UI.

True

key_display

str | None

Replacement text for key, or None to use default.

None

call_from_thread

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

Consider using post_message which is also thread-safe.

Parameters:

Name Type Description Default

callback

Callable[..., CallThreadReturnType | Awaitable[CallThreadReturnType]]

A callable to run.

required

*args

Any

Arguments to the callback.

()

**kwargs

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.

capture_mouse

capture_mouse(widget)

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

Parameters:

Name Type Description Default

widget

Widget | None

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

required

clear_notifications

clear_notifications()

Clear all the current notifications.

compose

compose()

Yield child widgets for a container.

This method should be implemented in a subclass.

copy_to_clipboard

copy_to_clipboard(text)

Copy text to the clipboard.

Note

This does not work on macOS Terminal, but will work on most other terminals.

Parameters:

Name Type Description Default

text

str

Text you wish to copy to the clipboard.

required

deliver_binary

deliver_binary(
    path_or_file,
    *,
    save_directory=None,
    save_filename=None,
    open_method="download",
    mime_type=None,
    name=None
)

Deliver a binary file to the end-user of the application.

If an IO object is supplied, it will be closed by this method and must not be used after it is supplied to this method.

If running in a terminal, this will save the file to the user's downloads directory.

If running via a web browser, this will initiate a download via a single-use URL.

This operation runs in a thread when running on web, so this method returning does not indicate that the file has been delivered.

After the file has been delivered, a DeliveryComplete message will be posted to this App, which contains the delivery_key returned by this method. By handling this message, you can add custom logic to your application that fires only after the file has been delivered.

Parameters:

Name Type Description Default

path_or_file

str | Path | BinaryIO

The path or file-like object to save.

required

save_directory

str | Path | None

The directory to save the file to. If None, the default "downloads" directory will be used. This argument is ignored when running via the web.

None

save_filename

str | None

The filename to save the file to. If None, the following logic applies to generate the filename: - If path_or_file is a file-like object, the filename will be taken from the name attribute if available. - If path_or_file is a path, the filename will be taken from the path. - If a filename is not available, a filename will be generated using the App's title and the current date and time.

None

open_method

Literal['browser', 'download']

The method to use to open the file. "browser" will open the file in the web browser, "download" will initiate a download. Note that this can sometimes be impacted by the browser's settings.

'download'

mime_type

str | None

The MIME type of the file or None to guess based on file extension. If no MIME type is supplied and we cannot guess the MIME type, from the file extension, the MIME type will be set to "application/octet-stream".

None

name

str | None

A user-defined named which will be returned in DeliveryComplete and DeliveryComplete.

None

Returns:

Type Description
str | None

The delivery key that uniquely identifies the file delivery.

deliver_screenshot

deliver_screenshot(
    filename=None, path=None, time_format=None
)

Deliver a screenshot of the app.

This with save the screenshot when running locally, or serve it when the app is running in a web browser.

Parameters:

Name Type Description Default

filename

str | None

Filename of SVG screenshot, or None to auto-generate a filename with the date and time.

None

path

str | None

Path to directory for output when saving locally (not used when app is running in the browser). Defaults to current working directory.

None

time_format

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 | None

The delivery key that uniquely identifies the file delivery.

deliver_text

deliver_text(
    path_or_file,
    *,
    save_directory=None,
    save_filename=None,
    open_method="download",
    encoding=None,
    mime_type=None,
    name=None
)

Deliver a text file to the end-user of the application.

If a TextIO object is supplied, it will be closed by this method and must not be used after this method is called.

If running in a terminal, this will save the file to the user's downloads directory.

If running via a web browser, this will initiate a download via a single-use URL.

After the file has been delivered, a DeliveryComplete message will be posted to this App, which contains the delivery_key returned by this method. By handling this message, you can add custom logic to your application that fires only after the file has been delivered.

Parameters:

Name Type Description Default

path_or_file

str | Path | TextIO

The path or file-like object to save.

required

save_directory

str | Path | None

The directory to save the file to.

None

save_filename

str | None

The filename to save the file to. If path_or_file is a file-like object, the filename will be generated from the name attribute if available. If path_or_file is a path the filename will be generated from the path.

None

encoding

str | None

The encoding to use when saving the file. If None, the encoding will be determined by supplied file-like object (if possible). If this is not possible, 'utf-8' will be used.

None

mime_type

str | None

The MIME type of the file or None to guess based on file extension. If no MIME type is supplied and we cannot guess the MIME type, from the file extension, the MIME type will be set to "text/plain".

None

name

str | None

A user-defined named which will be returned in DeliveryComplete and DeliveryComplete.

None

Returns:

Type Description
str | None

The delivery key that uniquely identifies the file delivery.

end_capture_print

end_capture_print(target)

End capturing of prints.

Parameters:

Name Type Description Default

target

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

result

ReturnType | None

Return value.

None

return_code

int

The return code. Use non-zero values for error codes.

0

message

RenderableType | None

Optional message to display on exit.

None

export_screenshot

export_screenshot(*, title=None, simplify=False)

Export an SVG screenshot of the current screen.

See also save_screenshot which writes the screenshot to a file.

Parameters:

Name Type Description Default

title

str | None

The title of the exported screenshot or None to use app title.

None

simplify

bool

Simplify the segments by combining contiguous segments with the same style.

False

get_child_by_id

get_child_by_id(id: str) -> Widget
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

id

str

The ID of the node to search for.

required

expect_type

type[ExpectType] | None

Require the object be of the supplied type, or use None to apply no type restriction.

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 a child of a give type.

Parameters:

Name Type Description Default

expect_type

type[ExpectType]

The type of the expected child.

required

Raises:

Type Description
NoMatches

If no valid child is found.

Returns:

Type Description
ExpectType

A widget.

get_css_variables

get_css_variables()

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

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

Returns:

Type Description
dict[str, str]

A mapping of variable name to value.

get_default_screen

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_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(binding)

Format a bound key for display in footer / key panel etc.

Note

You can implement this in a subclass if you want to change how keys are displayed in your app.

Parameters:

Name Type Description Default

binding

Binding

A Binding.

required

Returns:

Type Description
str

A string used to represent the key.

get_loading_widget

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_screen

get_screen(screen: ScreenType) -> ScreenType
get_screen(screen: str) -> Screen
get_screen(
    screen: str,
    screen_class: Type[ScreenType] | None = None,
) -> ScreenType
get_screen(
    screen: ScreenType,
    screen_class: Type[ScreenType] | None = None,
) -> ScreenType
get_screen(screen, screen_class=None)

Get an installed screen.

Example
my_screen = self.get_screen("settings", MyScreen)

Parameters:

Name Type Description Default

screen

Screen | str

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

required

screen_class

Type[Screen] | None

Class of expected screen, or None for any screen class.

None

Raises:

Type Description
KeyError

If the named screen doesn't exist.

Returns:

Type Description
Screen

A screen instance.

get_system_commands

get_system_commands(screen)

A generator of system commands used in the command palette.

Parameters:

Name Type Description Default

screen

Screen

The screen where the command palette was invoked from.

required

Implement this method in your App subclass if you want to add custom commands. Here is an example:

def get_system_commands(self, screen: Screen) -> Iterable[SystemCommand]:
    yield from super().get_system_commands(screen)
    yield SystemCommand("Bell", "Ring the bell", self.bell)

Note

Requires that SystemCommandsProvider is in App.COMMANDS class variable.

Yields:

Type Description
Iterable[SystemCommand]

SystemCommand instances.

get_theme

get_theme(theme_name)

Get a theme by name.

Parameters:

Name Type Description Default

theme_name

str

The name of the theme to get. May also be a comma separated list of names, to pick the first available theme.

required

Returns:

Type Description
Theme | None

A Theme instance and None if the theme doesn't exist.

get_theme_variable_defaults

get_theme_variable_defaults()

Get the default values for the variables used in a theme.

If the currently specified theme doesn't define a value for a variable, the value specified here will be used as a fallback.

If a variable is referenced in CSS but does not appear either here or in the theme, the CSS will fail to parse on startup.

This method allows applications to define their own variables, beyond those offered by Textual, which can then be overridden by a Theme.

Returns:

Type Description
dict[str, str]

A mapping of variable name (e.g. "my-button-background-color") to value.

dict[str, str]

Values can be any valid CSS value, e.g. "red 50%", "auto 90%",

dict[str, str]

"#ff0000", "rgb(255, 0, 0)", etc.

get_widget_at

get_widget_at(x, y)

Get the widget under the given coordinates.

Parameters:

Name Type Description Default

x

int

X coordinate.

required

y

int

Y coordinate.

required

Returns:

Type Description
tuple[Widget, Region]

The widget and the widget's screen region.

get_widget_by_id

get_widget_by_id(id: str) -> Widget
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

id

str

The ID to search for in the subtree

required

expect_type

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.

handle_bindings_clash

handle_bindings_clash(clashed_bindings, node)

Handle a clash between bindings.

Bindings clashes are likely due to users setting conflicting keys via their keymap.

This method is intended to be overridden by subclasses.

Textual will call this each time a clash is encountered - which may be on each keypress if a clashing widget is focused or is in the bindings chain.

Parameters:

Name Type Description Default

clashed_bindings

set[Binding]

The bindings that are clashing.

required

node

DOMNode

The node that has the clashing bindings.

required

install_screen

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 or switch_screen to make a new screen current.

Parameters:

Name Type Description Default

screen

Screen

Screen to install.

required

name

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.

is_mounted

is_mounted(widget)

Check if a widget is mounted.

Parameters:

Name Type Description Default

widget

Widget

A widget.

required

Returns:

Type Description
bool

True of the widget is mounted.

is_screen_installed

is_screen_installed(screen)

Check if a given screen has been installed.

Parameters:

Name Type Description Default

screen

Screen | str

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

required

Returns:

Type Description
bool

True if the screen is currently installed,

mount

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

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

Parameters:

Name Type Description Default

*widgets

Widget

The widget(s) to mount.

()

before

int | str | Widget | None

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.

None

after

int | str | Widget | None

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.

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_all(widgets, *, before=None, after=None)

Mount widgets from an iterable.

Parameters:

Name Type Description Default

widgets

Iterable[Widget]

An iterable of widgets.

required

before

int | str | Widget | None

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.

None

after

int | str | Widget | None

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.

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

notify(
    message,
    *,
    title="",
    severity="information",
    timeout=None
)

Create a notification.

Tip

This method is thread-safe.

Parameters:

Name Type Description Default

message

str

The message for the notification.

required

title

str

The title for the notification.

''

severity

SeverityLevel

The severity of the notification.

'information'

timeout

float | None

The timeout (in seconds) for the notification, or None for default.

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="")

open_url

open_url(url, *, new_tab=True)

Open a URL in the default web browser.

Parameters:

Name Type Description Default

url

str

The URL to open.

required

new_tab

bool

Whether to open the URL in a new tab.

True

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

*renderables

RenderableType

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

()

pop_screen

pop_screen()

Pop the current screen from the stack, and switch to the previous screen.

Returns:

Type Description
AwaitComplete

The screen that was replaced.

post_display_hook

post_display_hook()

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

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

Screen[ScreenResultType] | str

A Screen instance or the name of an installed screen.

required

callback

ScreenResultCallbackType[ScreenResultType] | None

An optional callback function that will be called if the screen is dismissed with a result.

None

wait_for_dismiss

bool

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.

False

Raises:

Type Description
NoActiveWorker

If using wait_for_dismiss outside of a worker.

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: str) -> Any
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

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()

Recompose the widget.

Recomposing will remove children and call self.compose again to remount.

refresh

refresh(*, repaint=True, layout=False, recompose=False)

Refresh the entire screen.

Parameters:

Name Type Description Default

repaint

bool

Repaint the widget (will call render() again).

True

layout

bool

Also layout widgets in the view.

False

recompose

bool

Re-compose the widget (will remove and re-mount children).

False

Returns:

Type Description
Self

The App instance.

refresh_css

refresh_css(animate=True)

Refresh CSS.

Parameters:

Name Type Description Default

animate

bool

Also execute CSS animations.

True

register_theme

register_theme(theme)

Register a theme with the app.

If the theme already exists, it will be overridden.

After registering a theme, you can activate it by setting the App.theme attribute. To retrieve a registered theme, use the App.get_theme method.

Parameters:

Name Type Description Default

theme

Theme

The theme to register.

required

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

mode

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()

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

headless

bool

Run in headless mode (no output).

False

inline

bool

Run the app inline (under the prompt).

False

inline_no_clear

bool

Don't clear the app output when exiting an inline app.

False

mouse

bool

Enable mouse support.

True

size

tuple[int, int] | None

Force terminal size to (WIDTH, HEIGHT), or None to auto-detect.

None

auto_pilot

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

action

str | ActionParseResult

Action encoded in a string.

required

default_namespace

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

headless

bool

Run in headless mode (no output).

False

inline

bool

Run the app inline (under the prompt).

False

inline_no_clear

bool

Don't clear the app output when exiting an inline app.

False

mouse

bool

Enable mouse support.

True

size

tuple[int, int] | None

Force terminal size to (WIDTH, HEIGHT), or None to auto-detect.

None

auto_pilot

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

headless

bool

Run in headless mode (no output or input).

True

size

tuple[int, int] | None

Force terminal size to (WIDTH, HEIGHT), or None to auto-detect.

(80, 24)

tooltips

bool

Enable tooltips when testing.

False

notifications

bool

Enable notifications when testing.

False

message_hook

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

filename

str | None

Filename of SVG screenshot, or None to auto-generate a filename with the date and time.

None

path

str | None

Path to directory for output. Defaults to current working directory.

None

time_format

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.

search_commands

search_commands(
    commands, placeholder="Search for commands…"
)

Show a list of commands in the app.

Parameters:

Name Type Description Default

commands

Sequence[CommandListItem]

A list of SimpleCommand instances.

required

placeholder

str

Placeholder text for the search field.

'Search for commands…'

Returns:

Name Type Description
AwaitMount AwaitMount

An awaitable that resolves when the commands are shown.

search_themes

search_themes()

Show a fuzzy search command palette containing all registered themes.

Selecting a theme in the list will change the app's theme.

set_focus

set_focus(widget, scroll_visible=True)

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

Parameters:

Name Type Description Default

widget

Widget | None

Widget to focus.

required

scroll_visible

bool

Scroll widget in to view.

True

set_keymap

set_keymap(keymap)

Set the keymap, a mapping of binding IDs to key strings.

Bindings in the keymap are used to override default key bindings, i.e. those defined in BINDINGS class variables.

Bindings with IDs that are present in the keymap will have their key string replaced with the value from the keymap.

Parameters:

Name Type Description Default

keymap

Keymap

A mapping of binding IDs to key strings.

required

simulate_key

simulate_key(key)

Simulate a key press.

This will perform the same action as if the user had pressed the key.

Parameters:

Name Type Description Default

key

str

Key to simulate. May also be the name of a key, e.g. "space".

required

stop_animation async

stop_animation(attribute, complete=True)

Stop an animation on an attribute.

Parameters:

Name Type Description Default

attribute

str

Name of the attribute whose animation should be stopped.

required

complete

bool

Should the animation be set to its final value?

True
Note

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

suspend

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.

Example
with self.suspend():
    os.system("emacs -nw")

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

mode

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.

switch_screen

switch_screen(screen)

Switch to another screen by replacing the top of the screen stack with a new screen.

Parameters:

Name Type Description Default

screen

Screen | str

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

required

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

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.

unregister_theme

unregister_theme(theme_name)

Unregister a theme with the app.

Parameters:

Name Type Description Default

theme_name

str

The name of the theme to unregister.

required

update_keymap

update_keymap(keymap)

Update the App's keymap, merging with keymap.

If a Binding ID exists in both the App's keymap and the keymap argument, the keymap argument takes precedence.

Parameters:

Name Type Description Default

keymap

Keymap

A mapping of binding IDs to key strings.

required

update_styles

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.

validate_sub_title

validate_sub_title(sub_title)

Make sure the subtitle is set to a string.

validate_title

validate_title(title)

Make sure the title is set to a string.

AppError

Bases: Exception

Base class for general App related exceptions.

InvalidModeError

Bases: ModeError

Raised if there is an issue with a mode name.

InvalidThemeError

Bases: Exception

Raised when an invalid theme is set.

ModeError

Bases: Exception

Base class for exceptions related to modes.

ScreenError

Bases: Exception

Base class for exceptions that relate to screens.

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.

SystemCommand

Bases: NamedTuple

Defines a system command used in the command palette (yielded from get_system_commands).

callback instance-attribute

callback

A callback to invoke when the command is selected.

discover class-attribute instance-attribute

discover = True

Should the command show when the search is empty?

help instance-attribute

help

Additional help text, shown under the title.

title instance-attribute

title

The title of the command (used in search).

UnknownModeError

Bases: ModeError

Raised when attempting to use a mode that is not known.

get_system_commands_provider

get_system_commands_provider()

Callable to lazy load the system commands.

Returns:

Type Description
type[SystemCommandsProvider]

System commands class.