Skip to content

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: TypeAlias = (
    "Callable[[Pilot[object]], Coroutine[Any, Any, None]]"
)

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

CSSPathType module-attribute

CSSPathType = Union[
    str, PurePath, List[Union[str, PurePath]]
]

Valid ways of specifying paths to CSS files.

ActionError class

Bases: Exception

Base class for exceptions relating to actions.

ActiveModeError class

Bases: ModeError

Raised when attempting to remove the currently active mode.

App class

def __init__(
    self, driver_class=None, css_path=None, watch_css=False
):

Bases: Generic[ReturnType], DOMNode

The base class for Textual Applications.

Parameters
Parameter Default Description
driver_class
Type[Driver] | None
None

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

css_path
CSSPathType | None
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.

watch_css
bool
False

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

Raises
Type Description
CssPathError

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

AUTO_FOCUS class-attribute

AUTO_FOCUS: str | None = '*'

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.

COMMANDS class-attribute

COMMANDS: set[
    type[Provider] | Callable[[], type[Provider]]
] = {get_system_commands}

Command providers used by the command palette.

Should be a set of command.Provider classes.

CSS class-attribute

CSS: str = ''

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: CSSPathType | None = None

File paths to load CSS from.

ENABLE_COMMAND_PALETTE class-attribute

ENABLE_COMMAND_PALETTE: bool = True

Should the command palette be enabled for the application?

MODES class-attribute

MODES: dict[str, str | Screen | Callable[[], Screen]] = {}

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,
    }

    ...

SCREENS class-attribute

SCREENS: dict[
    str, Screen[Any] | Callable[[], Screen[Any]]
] = {}

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

SUB_TITLE instance-attribute class-attribute

SUB_TITLE: str | None = 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.

TITLE instance-attribute class-attribute

TITLE: str | None = 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.

animation_level instance-attribute

animation_level: AnimationLevel = (
    constants.TEXTUAL_ANIMATIONS
)

Determines what type of animations the app will display.

See textual.constants.TEXTUAL_ANIMATIONS.

animator property

animator: Animator

The animator object.

ansi_theme property

ansi_theme: TerminalTheme

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 instance-attribute class-attribute

ansi_theme_dark = Reactive(MONOKAI, init=False)

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

ansi_theme_light instance-attribute class-attribute

ansi_theme_light = Reactive(ALABASTER, init=False)

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

app_focus instance-attribute class-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.

children 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
Type Description
Sequence['Widget']

A sequence of widgets.

current_mode property

current_mode: str

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.

dark instance-attribute class-attribute

dark: Reactive[bool] = Reactive(True, compute=False)

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

Modify this attribute to switch between light and dark themes.

Example
self.app.dark = not self.app.dark  # Toggle dark mode

debug property

debug: bool

Is debug mode enabled?

focused property

focused: Widget | None

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

is_headless: bool

Is the app running in 'headless' mode?

Headless mode is used when running tests with run_test.

is_inline property

is_inline: bool

Is the app running in 'inline' mode?

log property

log: Logger

The textual logger.

Example
self.log("Hello, World!")
self.log(self.tree)
Returns
Type Description
Logger

A Textual logger.

namespace_bindings 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
Type Description
dict[str, tuple[DOMNode, Binding]]

A map of keys to a tuple containing the DOMNode and Binding that key corresponds to.

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

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

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

screen property

screen: Screen[object]

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: Sequence[Screen[Any]]

A snapshot of the current screen stack.

Returns
Type Description
Sequence[Screen[Any]]

A snapshot of the current state of the screen stack.

scroll_sensitivity_x instance-attribute

scroll_sensitivity_x: float = 4.0

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

scroll_sensitivity_y instance-attribute

scroll_sensitivity_y: float = 2.0

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

size property

size: Size

The size of the terminal.

Returns
Type Description
Size

Size of the terminal.

sub_title instance-attribute class-attribute

sub_title: Reactive[str] = (
    self.SUB_TITLE if self.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.

title instance-attribute class-attribute

title: Reactive[str] = (
    self.TITLE
    if self.TITLE is not None
    else f"{self.__class__.__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: bool = self.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: WorkerManager

The worker manager.

Returns
Type Description
WorkerManager

An object to manage workers.

action_add_class async

def action_add_class(self, selector, class_name):

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

Parameters
Parameter Default Description
selector
str
required

Selects the widget to add the class to.

class_name
str
required

The class to add to the selected widget.

action_back async

def action_back(self):

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

def action_bell(self):

An action to play the terminal 'bell'.

action_check_bindings async

def action_check_bindings(self, key):

An action to handle a key press using the binding system.

Parameters
Parameter Default Description
key
str
required

The key to process.

action_command_palette method

def action_command_palette(self):

Show the Textual command palette.

action_focus async

def action_focus(self, widget_id):

An action to focus the given widget.

Parameters
Parameter Default Description
widget_id
str
required

ID of widget to focus.

action_focus_next method

def action_focus_next(self):

An action to focus the next widget.

action_focus_previous method

def action_focus_previous(self):

An action to focus the previous widget.

action_pop_screen async

def action_pop_screen(self):

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

action_push_screen async

def action_push_screen(self, screen):

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

Parameters
Parameter Default Description
screen
str
required

Name of the screen.

action_quit async

def action_quit(self):

An action to quit the app as soon as possible.

action_remove_class async

def action_remove_class(self, selector, class_name):

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

Parameters
Parameter Default Description
selector
str
required

Selects the widget to remove the class from.

class_name
str
required

The class to remove from the selected widget.

action_screenshot method

def action_screenshot(self, filename=None, path='./'):

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

Parameters
Parameter Default Description
filename
str | None
None

Filename of screenshot, or None to auto-generate.

path
str
'./'

Path to directory. Defaults to current working directory.

action_suspend_process method

def action_suspend_process(self):

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

def action_switch_mode(self, mode):

An action that switches to the given mode..

action_switch_screen async

def action_switch_screen(self, screen):

An action to switch screens.

Parameters
Parameter Default Description
screen
str
required

Name of the screen.

action_toggle_class async

def action_toggle_class(self, selector, class_name):

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

Parameters
Parameter Default Description
selector
str
required

Selects the widget to toggle the class on.

class_name
str
required

The class to toggle on the selected widget.

action_toggle_dark method

def action_toggle_dark(self):

An action to toggle dark mode.

add_mode method

def add_mode(self, mode, base_screen):

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

Parameters
Parameter Default Description
mode
str
required

The new mode.

base_screen
str | Screen | Callable[[], Screen]
required

The base screen associated with the given mode.

Raises
Type Description
InvalidModeError

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

animate method

def animate(
    self,
    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
Parameter Default Description
attribute
str
required

Name of the attribute to animate.

value
float | Animatable
required

The value to animate to.

final_value
object
...

The final value of the animation.

duration
float | None
None

The duration (in seconds) of the animation.

speed
float | None
None

The speed of the animation.

delay
float
0.0

A delay (in seconds) before the animation starts.

easing
EasingFunction | str
DEFAULT_EASING

An easing method.

on_complete
CallbackType | None
None

A callable to invoke when the animation is finished.

level
AnimationLevel
'full'

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

batch_update method

def batch_update(self):

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

begin_capture_print method

def begin_capture_print(self, 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
Parameter Default Description
target
MessageTarget
required

The widget where print content will be sent.

stdout
bool
True

Capture stdout.

stderr
bool
True

Capture stderr.

bell method

def bell(self):

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 method

def bind(
    self,
    keys,
    action,
    *,
    description="",
    show=True,
    key_display=None
):

Bind a key to an action.

Parameters
Parameter Default Description
keys
str
required

A comma separated list of keys, i.e.

action
str
required

Action to bind to.

description
str
''

Short description of action.

show
bool
True

Show key in UI.

key_display
str | None
None

Replacement text for key, or None to use default.

call_from_thread method

def call_from_thread(self, 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
Parameter Default Description
callback
Callable[..., CallThreadReturnType | Awaitable[CallThreadReturnType]]
required

A callable to run.

*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 method

def capture_mouse(self, widget):

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

Parameters
Parameter Default Description
widget
Widget | None
required

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

check_bindings async

def check_bindings(self, 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.

Parameters
Parameter Default Description
key
str
required

A key.

priority
bool
False

If True check from App down, otherwise from focused up.

Returns
Type Description
bool

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

clear_notifications method

def clear_notifications(self):

Clear all the current notifications.

compose method

def compose(self):

Yield child widgets for a container.

This method should be implemented in a subclass.

copy_to_clipboard method

def copy_to_clipboard(self, text):

Copy text to the clipboard.

Note

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

Parameters
Parameter Default Description
text
str
required

Text you wish to copy to the clipboard.

end_capture_print method

def end_capture_print(self, target):

End capturing of prints.

Parameters
Parameter Default Description
target
MessageTarget
required

The widget that was capturing prints.

exit method

def exit(self, result=None, return_code=0, message=None):

Exit the app, and return the supplied result.

Parameters
Parameter Default Description
result
ReturnType | None
None

Return value.

return_code
int
0

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

message
RenderableType | None
None

Optional message to display on exit.

export_screenshot method

def export_screenshot(self, *, title=None):

Export an SVG screenshot of the current screen.

See also save_screenshot which writes the screenshot to a file.

Parameters
Parameter Default Description
title
str | None
None

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

get_child_by_id method

def get_child_by_id(self, id, expect_type=None):

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

Parameters
Parameter Default Description
id
str
required

The ID of the node to search for.

expect_type
type[ExpectType] | None
None

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

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 method

def get_child_by_type(self, expect_type):

Get a child of a give type.

Parameters
Parameter Default Description
expect_type
type[ExpectType]
required

The type of the expected child.

Raises
Type Description
NoMatches

If no valid child is found.

Returns
Type Description
ExpectType

A widget.

get_css_variables method

def get_css_variables(self):

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_driver_class method

def get_driver_class(self):

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 method

def get_key_display(self, 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
Parameter Default Description
key
str
required

The binding key string.

Returns
Type Description
str

The display string for the input key.

get_loading_widget method

def get_loading_widget(self):

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 method

def get_screen(self, screen):

Get an installed screen.

Parameters
Parameter Default Description
screen
Screen | str
required

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

Raises
Type Description
KeyError

If the named screen doesn't exist.

Returns
Type Description
Screen

A screen instance.

get_widget_at method

def get_widget_at(self, x, y):

Get the widget under the given coordinates.

Parameters
Parameter Default Description
x
int
required

X coordinate.

y
int
required

Y coordinate.

Returns
Type Description
tuple[Widget, Region]

The widget and the widget's screen region.

get_widget_by_id method

def get_widget_by_id(self, 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
Parameter Default Description
id
str
required

The ID to search for in the subtree

expect_type
type[ExpectType] | None
None

Require the object be of the supplied type, or None for any type. Defaults to 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 method

def install_screen(self, 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
Parameter Default Description
screen
Screen
required

Screen to install.

name
str
required

Unique name to identify the screen.

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 method

def is_mounted(self, widget):

Check if a widget is mounted.

Parameters
Parameter Default Description
widget
Widget
required

A widget.

Returns
Type Description
bool

True of the widget is mounted.

is_screen_installed method

def is_screen_installed(self, screen):

Check if a given screen has been installed.

Parameters
Parameter Default Description
screen
Screen | str
required

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

Returns
Type Description
bool

True if the screen is currently installed,

mount method

def mount(self, *widgets, before=None, after=None):

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

Parameters
Parameter Default Description
*widgets
Widget
()

The widget(s) to mount.

before
int | str | Widget | None
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.

after
int | str | Widget | None
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.

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 method

def mount_all(self, widgets, *, before=None, after=None):

Mount widgets from an iterable.

Parameters
Parameter Default Description
widgets
Iterable[Widget]
required

An iterable of widgets.

before
int | str | Widget | None
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.

after
int | str | Widget | None
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.

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 method

def notify(
    self,
    message,
    *,
    title="",
    severity="information",
    timeout=Notification.timeout
):

Create a notification.

Tip

This method is thread-safe.

Parameters
Parameter Default Description
message
str
required

The message for the notification.

title
str
''

The title for the notification.

severity
SeverityLevel
'information'

The severity of the notification.

timeout
float
Notification.timeout

The timeout (in seconds) for the notification.

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 method

def panic(self, *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
Parameter Default Description
*renderables
RenderableType
()

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

pop_screen method

def pop_screen(self):

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

Returns
Type Description
Screen[object]

The screen that was replaced.

post_display_hook method

def post_display_hook(self):

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

push_screen method

def push_screen(
    self, screen, callback=None, wait_for_dismiss=False
):

Push a new screen on the screen stack, making it the current screen.

Parameters
Parameter Default Description
screen
Screen[ScreenResultType] | str
required

A Screen instance or the name of an installed screen.

callback
ScreenResultCallbackType[ScreenResultType] | None
None

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

wait_for_dismiss
bool
False

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
Type Description
NoActiveWorker

If using wait_for_dismiss outside of a worker.

Returns
Type Description
AwaitMount | asyncio.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

def push_screen_wait(self, 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
Parameter Default Description
screen
Screen[ScreenResultType] | str
required

A screen or the name of an installed screen.

Returns
Type Description
ScreenResultType | Any

The screen's result.

recompose async

def recompose(self):

Recompose the widget.

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

refresh method

def refresh(
    self, *, repaint=True, layout=False, recompose=False
):

Refresh the entire screen.

Parameters
Parameter Default Description
repaint
bool
True

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

layout
bool
False

Also layout widgets in the view.

recompose
bool
False

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

Returns
Type Description
Self

The App instance.

refresh_css method

def refresh_css(self, animate=True):

Refresh CSS.

Parameters
Parameter Default Description
animate
bool
True

Also execute CSS animations.

remove_mode method

def remove_mode(self, mode):

Removes a mode from the app.

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

Parameters
Parameter Default Description
mode
str
required

The mode to remove. It can't be the active mode.

Raises
Type Description
ActiveModeError

If trying to remove the active mode.

UnknownModeError

If trying to remove an unknown mode.

run method

def run(
    self,
    *,
    headless=False,
    inline=False,
    inline_no_clear=False,
    mouse=True,
    size=None,
    auto_pilot=None
):

Run the app.

Parameters
Parameter Default Description
headless
bool
False

Run in headless mode (no output).

inline
bool
False

Run the app inline (under the prompt).

inline_no_clear
bool
False

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

mouse
bool
True

Enable mouse support.

size
tuple[int, int] | None
None

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

auto_pilot
AutopilotCallbackType | None
None

An auto pilot coroutine.

Returns
Type Description
ReturnType | None

App return value.

run_action async

def run_action(self, 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
Parameter Default Description
action
str | ActionParseResult
required

Action encoded in a string.

default_namespace
object | None
None

Namespace to use if not provided in the action, or None to use app.

Returns
Type Description
bool

True if the event has been handled.

run_async async

def run_async(
    self,
    *,
    headless=False,
    inline=False,
    inline_no_clear=False,
    mouse=True,
    size=None,
    auto_pilot=None
):

Run the app asynchronously.

Parameters
Parameter Default Description
headless
bool
False

Run in headless mode (no output).

inline
bool
False

Run the app inline (under the prompt).

inline_no_clear
bool
False

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

mouse
bool
True

Enable mouse support.

size
tuple[int, int] | None
None

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

auto_pilot
AutopilotCallbackType | None
None

An auto pilot coroutine.

Returns
Type Description
ReturnType | None

App return value.

run_test async

def run_test(
    self,
    *,
    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
async with app.run_test() as pilot:
    await pilot.click("#Button.ok")
    assert ...
Parameters
Parameter Default Description
headless
bool
True

Run in headless mode (no output or input).

size
tuple[int, int] | None
(80, 24)

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

tooltips
bool
False

Enable tooltips when testing.

notifications
bool
False

Enable notifications when testing.

message_hook
Callable[[Message], None] | None
None

An optional callback that will be called each time any message arrives at any message pump in the app.

save_screenshot method

def save_screenshot(
    self, filename=None, path=None, time_format=None
):

Save an SVG screenshot of the current screen.

Parameters
Parameter Default Description
filename
str | None
None

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

path
str | None
None

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

time_format
str | None
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.

Returns
Type Description
str

Filename of screenshot.

set_focus method

def set_focus(self, widget, scroll_visible=True):

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

Parameters
Parameter Default Description
widget
Widget | None
required

Widget to focus.

scroll_visible
bool
True

Scroll widget in to view.

stop_animation async

def stop_animation(self, attribute, complete=True):

Stop an animation on an attribute.

Parameters
Parameter Default Description
attribute
str
required

Name of the attribute whose animation should be stopped.

complete
bool
True

Should the animation be set to its final value?

Note

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

suspend method

def suspend(self):

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 method

def switch_mode(self, mode):

Switch to a given mode.

Parameters
Parameter Default Description
mode
str
required

The mode to switch to.

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 method

def switch_screen(self, screen):

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

Parameters
Parameter Default Description
screen
Screen | str
required

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

uninstall_screen method

def uninstall_screen(self, 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
Parameter Default Description
screen
Screen | str
required

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

Returns
Type Description
str | None

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

update_styles method

def update_styles(self, 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 method

def validate_sub_title(self, sub_title):

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

validate_title method

def validate_title(self, title):

Make sure the title is set to a string.

watch_dark method

def watch_dark(self, dark):

Watches the dark bool.

This method handles the transition between light and dark mode when you change the dark attribute.

AppError class

Bases: Exception

Base class for general App related exceptions.

InvalidModeError class

Bases: ModeError

Raised if there is an issue with a mode name.

ModeError class

Bases: Exception

Base class for exceptions related to modes.

ScreenError class

Bases: Exception

Base class for exceptions that relate to screens.

ScreenStackError class

Bases: ScreenError

Raised when trying to manipulate the screen stack incorrectly.

SuspendNotSupported class

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.

UnknownModeError class

Bases: ModeError

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

get_system_commands function

def get_system_commands():

Callable to lazy load the system commands.

Returns
Type Description
type[SystemCommands]

System commands class.