from textual.app import App, ComposeResult
from textual.widgets import Header, Footer, Label
from textual.reactive import reactive
from textual.containers import Center
from textual.color import Color
from datetime import datetime, timedelta
import time
import asyncio
from textual.design import ColorSystem
from textual.screen import Screen
class TimerApp(App):
"""
A TUI timer application built with Textual.
"""
CSS_PATH = "timer.tcss" # Load custom styles from timer.tcss
BINDINGS = [
("d", "toggle_dark", "Toggle dark mode"),
("r", "reset_timer", "Reset Timer"),
("q", "quit", "Quit"),
]
timer_duration = reactive(timedelta(minutes=1)) # Default duration (1 minute)
time_remaining = reactive(timedelta(minutes=1))
is_running = reactive(False)
is_finished = reactive(False)
def compose(self) -> ComposeResult:
"""Compose the UI."""
yield Header(show_clock=True)
yield Footer()
yield Center(
BigTime(self.time_remaining)
) # Wrap with Center to center the text
yield Center(
Label(id="status", style="italic") # Status label
)
def on_mount(self) -> None:
"""Set up the timer on app startup."""
self.time_remaining = self.timer_duration
self.is_running = False
self.is_finished = False
self.update_status()
self.run_timer()
async def run_timer(self) -> None:
"""Run the timer until it reaches zero."""
while self.is_running and self.time_remaining > timedelta(0):
self.time_remaining -= timedelta(seconds=1)
await asyncio.sleep(1)
if self.time_remaining <= timedelta(0):
self.is_running = False
self.is_finished = True
self.update_status()
await self.flash_screen() # Flash when timer hits zero
def watch_time_remaining(self, time_remaining: timedelta) -> None:
"""Update the big time display when the time remaining changes."""
self.query_one(BigTime).time_remaining = time_remaining
def action_toggle_dark(self) -> None:
"""Toggle dark mode."""
self.dark = not self.dark
def action_reset_timer(self) -> None:
"""Reset the timer."""
self.time_remaining = self.timer_duration
self.is_running = False
self.is_finished = False
self.update_status()
async def on_click(self) -> None:
"""Start/stop the timer on click."""
self.is_running = not self.is_running
if self.is_running:
self.is_finished = False
asyncio.create_task(self.run_timer()) # start the task
self.update_status()
def update_status(self) -> None:
"""Update the status label at the bottom."""
status_label = self.query_one("#status", Label) # Select by ID
if self.is_finished:
status_label.update("TIME'S UP!")
elif self.is_running:
status_label.update("Running...")
else:
status_label.update("Click to Start/Pause")
async def flash_screen(self) -> None:
"""Flash the screen when the timer finishes."""
original_styles = self.styles.background, self.styles.color
flash_bg = self.app.design.error
flash_fg = self.app.design.panel
for _ in range(5): # Flash 5 times
self.styles.background = flash_bg
self.styles.color = flash_fg
await asyncio.sleep(0.3)
self.styles.background = original_styles[0]
self.styles.color = original_styles[1]
await asyncio.sleep(0.3)
class BigTime(Label):
"""A widget to display the remaining time in a large format."""
time_remaining = reactive(timedelta(seconds=0))
def watch_time_remaining(self, time_remaining: timedelta) -> None:
"""Update the display when the time remaining changes."""
minutes, seconds = divmod(int(time_remaining.total_seconds()), 60)
time_str = f"{minutes:02}:{seconds:02}"
self.update(time_str)
def on_resize(self) -> None:
"""Adjust font size to fit the available space."""
width, height = self.size
font_size = min(width // 4, height // 2) # Adjust divisors as needed
self.styles.font_size = font_size
self.styles.width = width
self.styles.height = height
def render(self) -> str:
"""Render the time string."""
minutes, seconds = divmod(int(self.time_remaining.total_seconds()), 60)
time_str = f"{minutes:02}:{seconds:02}"
return time_str
if __name__ == "__main__":
app = TimerApp()
app.run()
timer.tcss:
BigTime {
width: auto;
height: auto;
content-align: center middle;
text-align: center;
font-family: monospace; /* Use a monospace font for alignment */
}
#status {
margin-top: 1; /* Add some space above the status label */
}
Key improvements and explanations:
- Clearer Structure: The code is organized with distinct classes for the application (
TimerApp) and the large time display (BigTime). This makes it more readable and maintainable.
- CSS Styling: Uses a separate
timer.tcss file for styling, which is the recommended Textual approach. This keeps the Python code clean. Crucially, I added font-family: monospace to the CSS to ensure the numbers are aligned correctly in the big timer display. Also made the BigTime widget width: auto and height: auto so the on_resize callback can properly size the text. Added #status selector to provide some top margin for the status label.
- Reactive Variables: Uses
reactive variables for timer_duration, time_remaining, is_running, and is_finished. This ensures that the UI updates automatically whenever these values change. The watch_time_remaining method is used to update the BigTime widget when time_remaining changes.
on_resize Callback: The BigTime widget includes an on_resize method that dynamically adjusts the font size based on the available width and height of the widget. This is key for making the time display adapt to different terminal sizes. The divisors width // 4, height // 2 can be adjusted to fine-tune how large the numbers are.
- Centering: Uses
Center containers to ensure that both the time display and the status label are centered horizontally and vertically within the terminal.
- Status Label: Adds a status label at the bottom to display messages like "Running...", "Click to Start/Pause", and "TIME'S UP!". The
update_status() method updates this label based on the timer's state.
- Screen Flashing: The
flash_screen() function now correctly flashes the screen by temporarily changing the background and foreground colors of the entire application. It now correctly restores the original colors. It uses the design tokens (self.app.design.error, self.app.design.panel) for colors, so the flash color will match the theme.
- Error Handling/Clarity: The logic for starting and stopping the timer is more robust. The
is_finished flag prevents the timer from running after it has already finished.
- Bindings: Added bindings for resetting the timer () and quitting ().
How to run:
- Save: Save the Python code as
timer.py and the CSS code as timer.tcss in the same directory.
- Install Textual:
pip install textual
- Run:
python timer.py
Now, when the timer reaches zero, the terminal window will flash red five times to visually alert you. The numbers should also scale up or down to fit the available space in the terminal. The status bar at the bottom will provide feedback. Click anywhere to start or pause the timer.