From d945029b9a7216aa1f633ff2d3151ff776c3a61d Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Sun, 4 Sep 2022 21:10:15 +0100 Subject: [PATCH] mounting --- docs/examples/app/widgets02.py | 15 +++++++++++++++ docs/guide/app.md | 17 ++++++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 docs/examples/app/widgets02.py diff --git a/docs/examples/app/widgets02.py b/docs/examples/app/widgets02.py new file mode 100644 index 000000000..9fb52c228 --- /dev/null +++ b/docs/examples/app/widgets02.py @@ -0,0 +1,15 @@ +from textual.app import App +from textual.widgets import Welcome + + +class WelcomeApp(App): + def on_key(self) -> None: + self.mount(Welcome()) + + def on_button_pressed(self) -> None: + self.exit() + + +app = WelcomeApp() +if __name__ == "__main__": + app.run() diff --git a/docs/guide/app.md b/docs/guide/app.md index f578b5a5c..5e029e72c 100644 --- a/docs/guide/app.md +++ b/docs/guide/app.md @@ -88,7 +88,22 @@ The following example imports a builtin Welcome widget and yields it from compos When you run this code, Textual will *mount* the Welcome widget which contains a Markdown content area and a button: -```{.textual path="docs/examples/app/widgets01.py"} +```{.textual path="docs/examples/app/widgets01.py" title="widgets01.py" } ``` Notice the `on_button_pressed` method which handles the [Button.Pressed][textual.widgets.Button] event send by the button contained in the Welcome widget. The handlers calls [App.exit()][textual.app.App] to exit the app. + +### Mounting + +While composing is the preferred way of adding widgets when your app starts it is sometimes necessary to add new widget(s) in response to events. You can do this by calling [mount()](textual.widget.Widget.mount) which will add a new widget to the UI. + +Here's an app which adds the welcome widget in response to any key press: + +```python title="widgets02.py" +--8<-- "docs/examples/app/widgets02.py" +``` + +When you first run this you will get a blank screen. Press any key to add the welcome widget. You can even press a key multiple times to add several widgets. + +```{.textual path="docs/examples/app/widgets02.py" title="widgets02.py" press="a,a,a,down,down,down,down,down,down,_,_,_,_,_,_"} +```