File: set_reactive01.py

package info (click to toggle)
textual 2.1.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 55,084 kB
  • sloc: python: 85,423; lisp: 1,669; makefile: 101
file content (67 lines) | stat: -rw-r--r-- 1,579 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from textual.app import App, ComposeResult
from textual.containers import Horizontal
from textual.reactive import reactive, var
from textual.widgets import Label

GREETINGS = [
    "Bonjour",
    "Hola",
    "こんにちは",
    "你好",
    "안녕하세요",
    "Hello",
]


class Greeter(Horizontal):
    """Display a greeting and a name."""

    DEFAULT_CSS = """
    Greeter {
        width: auto;
        height: 1;
        & Label {
            margin: 0 1;
        }
    }
    """
    greeting: reactive[str] = reactive("")
    who: reactive[str] = reactive("")

    def __init__(self, greeting: str = "Hello", who: str = "World!") -> None:
        super().__init__()
        self.greeting = greeting  # (1)!
        self.who = who

    def compose(self) -> ComposeResult:
        yield Label(self.greeting, id="greeting")
        yield Label(self.who, id="name")

    def watch_greeting(self, greeting: str) -> None:
        self.query_one("#greeting", Label).update(greeting)  # (2)!

    def watch_who(self, who: str) -> None:
        self.query_one("#who", Label).update(who)


class NameApp(App):

    CSS = """
    Screen {
        align: center middle;
    }
    """
    greeting_no: var[int] = var(0)
    BINDINGS = [("space", "greeting")]

    def compose(self) -> ComposeResult:
        yield Greeter(who="Textual")

    def action_greeting(self) -> None:
        self.greeting_no = (self.greeting_no + 1) % len(GREETINGS)
        self.query_one(Greeter).greeting = GREETINGS[self.greeting_no]


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