Creare una TUI in Python con asciimatics

Mattepuffo's logo
Creare una TUI in Python con asciimatics

Creare una TUI in Python con asciimatics

asciimatics è una libreria per Python che ci consente anche di creare una TUI.

In verità fa anche altre cose, ma noi la useremo con questo scopo.

Alla fine creeremo un form da riempire che visualizzerà i dati inseriti.

Possiamo installarla con pip:

pip install asciimatics

Qui sotto un pò di codice:

from asciimatics.widgets import Frame, Layout, Text, Button, Divider, Label, PopUpDialog
from asciimatics.screen import Screen
from asciimatics.exceptions import ResizeScreenError, StopApplication
from asciimatics.scene import Scene
import re
import sys

EMAIL_RE = re.compile(r"^[^@ \t\r\n]+@[^@ \t\r\n]+\.[^@ \t\r\n]+$")

class UserForm(Frame):
    def __init__(self, screen):
        height = 13
        width = 60
        x = (screen.width - width) // 2
        y = (screen.height - height) // 2
        super(UserForm, self).__init__(screen,
            height,
            width,
            x=x,
            y=y,
            has_shadow=True,
            name="UserForm")

        layout = Layout([1])
        self.add_layout(layout)

        layout.add_widget(Label("Compila il form e premi 'Invia'"), 0)
        layout.add_widget(Divider(), 0)

        self._nome = Text("Nome:", "nome")
        self._cognome = Text("Cognome:", "cognome")
        self._email = Text("Email:", "email")

        layout.add_widget(self._nome)
        layout.add_widget(self._cognome)
        layout.add_widget(self._email)

        layout.add_widget(Divider(), 0)

        layout_buttons = Layout([1, 1])
        self.add_layout(layout_buttons)
        layout_buttons.add_widget(Button("Invia", self._on_submit), 0)
        layout_buttons.add_widget(Button("Esci", self._on_quit), 1)

        self.fix()

    def _on_quit(self):
        raise StopApplication("Utente ha chiuso il form")

    def _on_submit(self):
        # Importante: salva i valori correnti del form
        self.save()

        data = self.data
        nome = (data.get("nome") or "").strip()
        cognome = (data.get("cognome") or "").strip()
        email = (data.get("email") or "").strip()

        errors = []
        if not nome:
            errors.append("Nome vuoto")
        if not cognome:
            errors.append("Cognome vuoto")
        if not email:
            errors.append("Email vuota")
        elif not EMAIL_RE.match(email):
            errors.append("Email non valida")

        if errors:
            msg = "Errori:\n- " + "\n- ".join(errors)
            self.scene.add_effect(PopUpDialog(self.screen, msg, ["OK"]))
            return

        summary = f"Nome: {nome}\nCognome: {cognome}\nEmail: {email}"
        self.scene.add_effect(PopUpDialog(self.screen, "Dati inviati con successo:\n\n" + summary, ["OK"]))

def demo(screen):
    form = UserForm(screen)
    scenes = [Scene([form], -1)]
    screen.play(scenes, stop_on_resize=True)

if __name__=="__main__":
    while True:
        try:
            Screen.wrapper(demo)
            sys.exit(0)
        except ResizeScreenError:
            continue
        except StopApplication as e:
            print("\nApplicazione terminata:", e)
            sys.exit(0)

Enjoy!


Condividi

Commentami!