|
| 1 | +from datetime import datetime |
| 2 | + |
| 3 | +from pytz import timezone |
| 4 | + |
| 5 | +from textual.app import App, ComposeResult |
| 6 | +from textual.reactive import reactive |
| 7 | +from textual.widget import Widget |
| 8 | +from textual.widgets import Digits, Label |
| 9 | + |
| 10 | + |
| 11 | +class WorldClock(Widget): |
| 12 | + |
| 13 | + time: reactive[datetime] = reactive(datetime.now) |
| 14 | + |
| 15 | + def __init__(self, timezone: str) -> None: |
| 16 | + self.timezone = timezone |
| 17 | + super().__init__() |
| 18 | + |
| 19 | + def compose(self) -> ComposeResult: |
| 20 | + yield Label(self.timezone) |
| 21 | + yield Digits() |
| 22 | + |
| 23 | + def watch_time(self, time: datetime) -> None: |
| 24 | + localized_time = time.astimezone(timezone(self.timezone)) |
| 25 | + self.query_one(Digits).update(localized_time.strftime("%H:%M:%S")) |
| 26 | + |
| 27 | + |
| 28 | +class WorldClockApp(App): |
| 29 | + CSS_PATH = "world_clock01.tcss" |
| 30 | + |
| 31 | + time: reactive[datetime] = reactive(datetime.now) |
| 32 | + |
| 33 | + def compose(self) -> ComposeResult: |
| 34 | + yield WorldClock("Europe/London") |
| 35 | + yield WorldClock("Europe/Paris") |
| 36 | + yield WorldClock("Asia/Tokyo") |
| 37 | + |
| 38 | + def update_time(self) -> None: |
| 39 | + self.time = datetime.now() |
| 40 | + |
| 41 | + def watch_time(self, time: datetime) -> None: |
| 42 | + for world_clock in self.query(WorldClock): # (1)! |
| 43 | + world_clock.time = time |
| 44 | + |
| 45 | + def on_mount(self) -> None: |
| 46 | + self.update_time() |
| 47 | + self.set_interval(1, self.update_time) |
| 48 | + |
| 49 | + |
| 50 | +if __name__ == "__main__": |
| 51 | + app = WorldClockApp() |
| 52 | + app.run() |
0 commit comments