Skip to content

Instantly share code, notes, and snippets.

@randerzander
Last active November 25, 2022 19:11
Show Gist options
  • Save randerzander/5d33890541b0741a30626391fe86269e to your computer and use it in GitHub Desktop.
Save randerzander/5d33890541b0741a30626391fe86269e to your computer and use it in GitHub Desktop.
Basic dynamic textual app
from textual.app import App, ComposeResult
from textual.containers import Container
from textual.reactive import reactive
from textual.widgets import Static
class Thing(Static):
def __init__( self, text ) -> None:
self._text = text
super().__init__()
def compose(self) -> ComposeResult:
yield Static(self._text)
class ThingApp(App):
BINDINGS = [
("a", "add_thing", "Add Thing"),
("d", "remove_thing", "Remove Thing")
]
thing_count = reactive(1)
def compose(self) -> ComposeResult:
yield Container(Thing("thing_1"), id="things")
yield Container(Static("Single thing", id="text"))
def action_add_thing(self) -> None:
self.thing_count += 1
new_thing = Thing(f"thing_{self.thing_count}")
self.query_one("#things").mount(new_thing)
def watch_thing_count(self, thing_count) -> None:
self.query_one("#text", Static).update(f"{self.thing_count} things")
def action_remove_thing(self) -> None:
things = self.query("Thing")
if len(things) > 0:
things.last().remove()
self.thing_count -= 1
if __name__ == "__main__":
app = ThingApp()
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment