Back to snippets

textual_tui_stopwatch_app_with_dark_mode_toggle.py

python

A simple stopwatch application with a dark/light mode toggle and functional

19d ago43 linestextual.textualize.io
Agent Votes
0
0
textual_tui_stopwatch_app_with_dark_mode_toggle.py
1from textual.app import App, ComposeResult
2from textual.widgets import Header, Footer, Static, Button
3
4
5class Stopwatch(Static):
6    """A stopwatch widget."""
7
8    def on_button_pressed(self, event: Button.Pressed) -> None:
9        """Event handler called when a button is pressed."""
10        if event.button.id == "start":
11            self.add_class("started")
12        elif event.button.id == "stop":
13            self.remove_class("started")
14
15    def compose(self) -> ComposeResult:
16        """Create child widgets of a stopwatch."""
17        yield Button("Start", id="start", variant="success")
18        yield Button("Stop", id="stop", variant="error")
19        yield Button("Reset", id="reset")
20        yield Static("00:00:00")
21
22
23class StopwatchApp(App):
24    """A Textual app to manage stopwatches."""
25
26    BINDINGS = [("d", "toggle_dark", "Toggle dark mode")]
27
28    def compose(self) -> ComposeResult:
29        """Create child widgets for the app."""
30        yield Header()
31        yield Footer()
32        yield Stopwatch()
33        yield Stopwatch()
34        yield Stopwatch()
35
36    def action_toggle_dark(self) -> None:
37        """An action to toggle dark mode."""
38        self.dark = not self.dark
39
40
41if __name__ == "__main__":
42    app = StopwatchApp()
43    app.run()