Widgets¶
In this chapter we will explore widgets in more detail, and how you can create custom widgets of your own.
What is a widget?¶
A widget is a component of your UI responsible for managing a rectangular region of the screen. Widgets may respond to events in much the same way as an app. In many respects, widgets are like mini-apps.
Information
Every widget runs in its own asyncio task.
Custom widgets¶
There is a growing collection of builtin widgets in Textual, but you can build entirely custom widgets that work in the same way.
The first step in building a widget is to import and extend a widget class. This can either be Widget which is the base class of all widgets, or one of its subclasses.
Let's create a simple custom widget to display a greeting.
from textual.app import App, ComposeResult, RenderResult
from textual.widget import Widget
class Hello(Widget):
"""Display a greeting."""
def render(self) -> RenderResult:
return "Hello, [b]World[/b]!"
class CustomApp(App):
def compose(self) -> ComposeResult:
yield Hello()
if __name__ == "__main__":
app = CustomApp()
app.run()
The highlighted lines define a custom widget class with just a render() method. Textual will display whatever is returned from render in the content area of your widget.
Note that the text contains tags in square brackets, i.e. [b].
This is content markup which allows you to embed various styles within your content.
If you run this you will find that World is in bold.
This (very simple) custom widget may be styled in the same way as builtin widgets, and targeted with CSS. Let's add some CSS to this app.
from textual.app import App, ComposeResult, RenderResult
from textual.widget import Widget
class Hello(Widget):
"""Display a greeting."""
def render(self) -> RenderResult:
return "Hello, [b]World[/b]!"
class CustomApp(App):
CSS_PATH = "hello02.tcss"
def compose(self) -> ComposeResult:
yield Hello()
if __name__ == "__main__":
app = CustomApp()
app.run()
The addition of the CSS has completely transformed our custom widget.
Static widget¶
While you can extend the Widget class, a subclass will typically be a better starting point. The Static class is a widget subclass which caches the result of render, and provides an update() method to update the content area.
Let's use Static to create a widget which cycles through "hello" in various languages.
from itertools import cycle
from textual.app import App, ComposeResult
from textual.widgets import Static
hellos = cycle(
[
"Hola",
"Bonjour",
"Guten tag",
"Salve",
"Nǐn hǎo",
"Olá",
"Asalaam alaikum",
"Konnichiwa",
"Anyoung haseyo",
"Zdravstvuyte",
"Hello",
]
)
class Hello(Static):
"""Display a greeting."""
def on_mount(self) -> None:
self.next_word()
def on_click(self) -> None:
self.next_word()
def next_word(self) -> None:
"""Get a new hello and update the content area."""
hello = next(hellos)
self.update(f"{hello}, [b]World[/b]!")
class CustomApp(App):
CSS_PATH = "hello03.tcss"
def compose(self) -> ComposeResult:
yield Hello()
if __name__ == "__main__":
app = CustomApp()
app.run()
Note that there is no render() method on this widget. The Static class is handling the render for us. Instead we call update() when we want to update the content within the widget.
The next_word method updates the greeting. We call this method from the mount handler to get the first word, and from a click handler to cycle through the greetings when we click the widget.
Default CSS¶
When building an app it is best to keep your CSS in an external file. This allows you to see all your CSS in one place, and to enable live editing. However if you intend to distribute a widget (via PyPI for instance) it can be convenient to bundle the code and CSS together. You can do this by adding a DEFAULT_CSS class variable inside your widget class.
Textual's builtin widgets bundle CSS in this way, which is why you can see nicely styled widgets without having to copy any CSS code.
Here's the Hello example again, this time the widget has embedded default CSS:
from itertools import cycle
from textual.app import App, ComposeResult
from textual.widgets import Static
hellos = cycle(
[
"Hola",
"Bonjour",
"Guten tag",
"Salve",
"Nǐn hǎo",
"Olá",
"Asalaam alaikum",
"Konnichiwa",
"Anyoung haseyo",
"Zdravstvuyte",
"Hello",
]
)
class Hello(Static):
"""Display a greeting."""
DEFAULT_CSS = """
Hello {
width: 40;
height: 9;
padding: 1 2;
background: $panel;
border: $secondary tall;
content-align: center middle;
}
"""
def on_mount(self) -> None:
self.next_word()
def on_click(self) -> None:
self.next_word()
def next_word(self) -> None:
"""Get a new hello and update the content area."""