Sunday, May 5, 2024
HomePythonMaking a Modal Dialog For Your TUIs in Textual

Making a Modal Dialog For Your TUIs in Textual


Textual is a Python bundle that you should use to create lovely text-based person interfaces (TUIs). In different phrases, you’ll be able to create a GUI in your terminal with Textual.

On this tutorial, you’ll discover ways to create a modal dialog in your terminal. Dialogs are nice methods to alert the person about one thing or get some enter. You additionally see dialogs used for things like settings or assist.

Let’s get began!

Including a Modal Dialog

Step one is to suppose up some type of software that wants a dialog. For this tutorial, you’ll create a kind permitting the person to enter a reputation and deal with. Your software gained’t save any information as that’s exterior the scope of this text, however it would show create the person interface and you’ll add that performance your self in a while, if you want.

To start out, create a brand new file and title it one thing like tui_kind.py. Then enter the next code:

from textual.app import App, ComposeResult
from textual.containers import Middle
from textual.containers import Grid
from textual.display screen import ModalScreen
from textual.widgets import Button, Footer, Header, Enter, Static, Label


class QuitScreen(ModalScreen):
    """Display with a dialog to give up."""

    def compose(self) -> ComposeResult:
        yield Grid(
            Label("Are you certain you need to give up?", id="query"),
            Button("Stop", variant="error", id="give up"),
            Button("Cancel", variant="main", id="cancel"),
            id="dialog",
        )

    def on_button_pressed(self, occasion: Button.Pressed) -> None:
        if occasion.button.id == "give up":
            self.app.exit()
        else:
            self.app.pop_screen()


class Kind(Static):
    def compose(self) -> ComposeResult:
        """
        Creates the primary UI components
        """
        yield Enter(id="first_name", placeholder="First Title")
        yield Enter(id="last_name", placeholder="Final Title")
        yield Enter(id="deal with", placeholder="Tackle")
        yield Enter(id="metropolis", placeholder="Metropolis")
        yield Enter(id="state", placeholder="State")
        yield Enter(id="zip_code", placeholder="Zip Code")
        yield Enter(id="electronic mail", placeholder="electronic mail")
        with Middle():
            yield Button("Save", id="save_button")


class AddressBookApp(App):
    CSS_PATH = "modal.tcss"
    BINDINGS = [("q", "request_quit", "Quit")]

    def compose(self) -> ComposeResult:
        """
        Lays out the primary UI elemens plus a header and footer
        """
        yield Header()
        yield Kind()
        yield Footer()

    def action_request_quit(self) -> None:
        """Motion to show the give up dialog."""
        self.push_screen(QuitScreen())


if __name__ == "__main__":
    app = AddressBookApp()
    app.run()

Since this code is slightly lengthy, you’ll evaluate it piece by piece. You’ll begin on the backside because the primary entry level is the AddressBookApp class.

Right here’s the code:

class AddressBookApp(App):
    CSS_PATH = "modal.tcss"
    BINDINGS = [("q", "request_quit", "Quit")]

    def compose(self) -> ComposeResult:
        """
        Lays out the primary UI elemens plus a header and footer
        """
        yield Header()
        yield Kind()
        yield Footer()

    def action_request_quit(self) -> None:
        """Motion to show the give up dialog."""
        self.push_screen(QuitScreen())


if __name__ == "__main__":
    app = AddressBookApp()
    app.run()

The AddressBookApp class is your software code. Right here, you create a header, the shape itself, and the footer of your software. When the person presses the q button, you additionally arrange an accelerator key or key binding that calls action_request_quit(). This can trigger your modal dialog to look!

However earlier than you have a look at that code, you need to take a look at your Kind’s code:

class Kind(Static):
    def compose(self) -> ComposeResult:
        """
        Creates the primary UI components
        """
        yield Enter(id="first_name", placeholder="First Title")
        yield Enter(id="last_name", placeholder="Final Title")
        yield Enter(id="deal with", placeholder="Tackle")
        yield Enter(id="metropolis", placeholder="Metropolis")
        yield Enter(id="state", placeholder="State")
        yield Enter(id="zip_code", placeholder="Zip Code")
        yield Enter(id="electronic mail", placeholder="electronic mail")
        with Middle():
            yield Button("Save", id="save_button")

The Kind class has a collection of Enter() widgets, that are textual content bins, that you would be able to enter your deal with info into. You specify a novel id for every widgets to present you a option to type every of them. You possibly can learn extra about how that works in Utilizing CSS to Fashion a Python TUI with Textual. The placeholder parameter enables you to add a label to the textual content management so the person is aware of what ought to be entered within the widget.

Now you might be prepared to maneuver on and have a look at your modal dialog code:

class QuitScreen(ModalScreen):
    """Display with a dialog to give up."""

    def compose(self) -> ComposeResult:
        yield Grid(
            Label("Are you certain you need to give up?", id="query"),
            Button("Stop", variant="error", id="give up"),
            Button("Cancel", variant="main", id="cancel"),
            id="dialog",
        )

    def on_button_pressed(self, occasion: Button.Pressed) -> None:
        if occasion.button.id == "give up":
            self.app.exit()
        else:
            self.app.pop_screen()

The QuitScreen class is made up of two capabilities:

  • compose() – Creates the widgets within the modal dialog
  • on_button_pressed() – The occasion handler that’s fired when a button is pressed

The applying will exit if the person presses the “Stop” button. In any other case, the dialog shall be dismissed, and also you’ll return to your kind display screen.

You possibly can type your software, together with the modal dialog, utilizing CSS. For those who scroll again as much as your software class, you’ll see that it refers to a CSS_PATH that factors to a file named modal.tcss.

Right here’s the CSS code that you just’ll want so as to add to that file:

QuitScreen {
    align: middle center;
}

#dialog {
    grid-size: 2;
    grid-gutter: 1 2;
    grid-rows: 1fr 3;
    padding: 0 1;
    width: 60;
    top: 11;
    border: thick $background 80%;
    background: $floor;
}

#query {
    column-span: 2;
    top: 1fr;
    width: 1fr;
    content-align: middle center;
}

Button {
    width: 100%;
}

This CSS will set the dimensions and placement of your modal dialog on the applying. You inform Textual that you really want the buttons to be centered and the dialog to be centered within the software.

To run your code, open up your terminal (or cmd.exe / Powershell on Home windows), navigate to the folder that has your code in it, and run this command:

python tui_form.py

Once you run this command, the preliminary display screen will appear like this:

To see the dialog, click on the Save button to take the main focus out of the textual content controls. Then hit the q button, and you will notice the next:

Textual form with modal dialog

You’ve achieved it! You created a modal dialog in your terminal!

Wrapping Up

Textual is a good Python bundle. You possibly can create wealthy, expressive person interfaces in your terminal. These GUIs are additionally light-weight and will be run in your browser through Textual-web.

Need to study extra about Textual? Take a look at a few of the following tutorials:

 

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments