Introduction to Asciimatics
Asciimatics is a comprehensive Python library designed to simplify the creation of text user interfaces (TUIs) and animations in the terminal. Whether you’re building a retro-styled game, a dynamic console application, or an engaging CLI tool, Asciimatics provides all the tools you need.
Getting Started with Asciimatics
To get started, you’ll first need to install Asciimatics. You can do this using pip:
pip install asciimatics
Creating a Simple Animation
With Asciimatics, creating animations is straightforward. The following example demonstrates how to create a simple ASCII animation:
from asciimatics.screen import Screen from asciimatics.scene import Scene from asciimatics.effects import Print from asciimatics.renderers import FigletText def demo(screen): scenes = [] effects = [ Print(screen, FigletText("Hello, World!"), screen.height//2 - 3) ] scenes.append(Scene(effects, -1)) screen.play(scenes) Screen.wrapper(demo)
Building a Menu-Driven Application
The next example shows how Asciimatics can be used to create a menu-driven application with multiple screens.
from asciimatics.screen import Screen from asciimatics.scene import Scene from asciimatics.widgets import Frame, Layout, Text, Button, Divider from asciimatics.exceptions import ResizeScreenError, NextScene class MainView(Frame): def __init__(self, screen): super(MainView, self).__init__(screen, screen.height, screen.width, has_border=True, name="Main") layout = Layout([1], fill_frame=True) self.add_layout(layout) layout.add_widget(Text("Name:", "name")) layout.add_widget(Divider()) layout.add_widget(Button("Quit", self._quit)) self.fix() def _quit(self): raise NextScene(None) def main_app(screen, scene): scenes = [ Scene([MainView(screen)], -1, name="Main"), ] screen.play(scenes, stop_on_resize=True, start_scene=scenes[0], allow_int=True) try: Screen.wrapper(main_app, catch_interrupt=False) except ResizeScreenError: pass
More Useful APIs
Asciimatics offers many more useful APIs for creating elaborate TUIs and animations. Here are a few more examples:
- Handling Keyboard Input:
from asciimatics.event import KeyboardEvent def handle_events(screen): while True: event = screen.get_event() if isinstance(event, KeyboardEvent): if event.key_code in [ord('Q'), ord('q')]: return
- Creating Custom Animations:
from asciimatics.effects import Effect class MyEffect(Effect): def _update(self, frame_no): self._screen.print_at("Custom Animation", 0, 0) self._stop = frame_no > 100 effects = [MyEffect(screen)] screen.play([Scene(effects, -1)])
With these powerful APIs, Asciimatics opens up a world of possibilities for text-based applications.
For more detailed documentation, visit the Asciimatics GitHub page.
Hash: b1e7fab599e0b49034a06940fe8ca94401f8d056d08c9fae1f5504e21cc81211