Skip to content

Actions

Actions are allow-listed functions with a string syntax you can embed in links and bind to keys. In this chapter we will discuss how to create actions and how to run them.

Action methods

Action methods are methods on your app or widgets prefixed with action_. Aside from the prefix these are regular methods which you could call directly if you wished.

Information

Action methods may be coroutines (defined with the async keyword).

Let's write an app with a simple action method.

actions01.py
from textual.app import App
from textual import events


class ActionsApp(App):
    def action_set_background(self, color: str) -> None:
        self.screen.styles.background = color

    def on_key(self, event: events.Key) -> None:
        if event.key == "r":
            self.action_set_background("red")


if __name__ == "__main__":
    app = ActionsApp()
    app.run()

The action_set_background method is an action method which sets the background of the screen. The key handler above will call this action method if you press the R key.

Although it is possible (and occasionally useful) to call action methods in this way, they are intended to be parsed from an action string. For instance, the string "set_background('red')" is an action string which would call self.action_set_background('red').

The following example replaces the immediate call with a call to run_action() which parses an action string and dispatches it to the appropriate method.

actions02.py
from textual import events
from textual.app import App


class ActionsApp(App):
    def action_set_background(self, color: str) -> None:
        self.screen.styles.background = color

    async def on_key(self, event: events.Key) -> None:
        if event.key == "r":
            await self.run_action("set_background('red')")


if __name__ == "__main__":