Tuesday, April 29, 2025
HomePythonAn Intro to Textual - Creating Textual content Person Interfaces with Python

An Intro to Textual – Creating Textual content Person Interfaces with Python


Textual is a Python bundle used to create cross-platform Textual content Person Interfaces (TUI). This may occasionally sound such as you’ll be making a person interface with ASCII-art, however that’s not the case.

Textual is kind of superior and means that you can add widgets to your terminal purposes, together with buttons, context switchers, scroll bars, checkboxes, inputs and extra.

Getting Began

The very first thing you must do is set up Textual. In case you solely wish to run Textual purposes, then the next pip comand is all you want:

python3 -m pip set up textual

Nevertheless, if you wish to write your individual Textual purposes, it’s best to run this command as a substitute:

python3 -m pip set up "textual[dev]"

That humorous little [dev] half will set up some additional dependencies that make growing Textual purposes simpler.

Run the Textual Demo

The Textual bundle comes with a demo. You’ll discover the demo is an effective way to see what forms of issues you are able to do with Textual.

Right here’s how one can run the demo:

python3 -m textual

If you run the command above in your terminal, it’s best to see one thing like the next seems:

You’ll be able to discover Textual within the demo and see the next options:

  • Widgets
  • Accelerators (i.e. CTRL+C)
  • CSS styling
  • and extra

Creating Your Personal Easy Utility

Whereas the demo is a good place to begin to get a really feel for what you are able to do with Textual, it’s at all times higher to dive into the docs and begin writing some actual code.

You’ll perceive how issues work a lot faster should you write the code your self after which begin altering the code piece by piece. By going by this iterative course of, you’ll learn to construct a bit at a time and also you’ll have a collection of small failures and successes, which is an effective way to construct up your confidence as you study.

Step one to take when making a Textual software is to import Textual and subclass the App() class. If you subclass App(), you create a Textual software. The App() class comprises all of the little fine details you must create your very personal terminal software.

To begin off, create a brand new Python file in your favourite textual content editor or IDE and title it hello_textual.py.

Subsequent, enter the next code into your new file:

from textual.app import App


class HelloWorld(App):
    ...


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

If you go to run your terminal software, it’s best to run it in a terminal. Some IDEs have a terminal built-in, reminiscent of VS Code and PyCharm. Textual might or might not look right in these terminals although.

Every time attainable, it is suggested that you simply run Textual purposes in your exterior terminal. Your purposes will look and behave higher there more often than not. On Mac, it is suggested that you simply use iTerm slightly than the built-in terminal because the built-in Terminal software hasn’t been up to date in fairly a while.

To run your new terminal software, you will have to run the next command:

python3 hello_textual.py

If you run this command, you will notice the next:

Hello Textual

Oops! That’s sort of like making a clean black field! That’s most likely not what you need in spite of everything.

To exit a Textual software, press CTRL+C. If you do, you’ll exit the appliance and return to the traditional terminal.

That was thrilling, however the person interface was very plain. You’ll be able to repair that up a bit by including a label within the subsequent part!

Including a Label

Now that you’re again to your unique terminal, return to your Python editor and create a brand new file. This time you’ll title it hello_textual2.py.

Enter the next code into your new Python file:

from textual.app import App, ComposeResult
from textual.widgets import Label


class HelloWorld(App):

    def compose(self) -> ComposeResult:
        yield Label("Hi there Textual")

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

Your HelloWorld() class was empty earlier than. Now you added a compose() technique. The compose() technique is the place you usually setup your widgets.

A widget is a person interface factor, reminiscent of a label, a textual content field, or a button. On this instance, you add a Label() with the textual content “Hi there World” in it.

Attempt working your new code in your terminal and it’s best to see one thing like this:

Hello Textual with label

Properly, that appears a bit higher than the unique. However it might be good to have a technique to shut your software with out utilizing CTRL+C.

One widespread technique to shut an software is with a Shut button. You’ll learn to add a kind of subsequent!

Including a Shut Button

If you create a person interface, you wish to talk with the person about how they will shut your software. A terminal software already has a technique to shut the terminal itself by means of its exit button.

Nevertheless, you normally desire a technique to shut your Textual software with out closing the terminal itself. You have got been utilizing CTRL+C for this.

However there’s a greater method! You’ll be able to add a Button widget and join an occasion handler to it to shut the perform.

To get began, open up a brand new Python file in your Python editor of alternative. Title this one hello_textual3.py after which enter the next code:

# hello_textual3.py

from textual.app import App, ComposeResult
from textual.widgets import Button, Label


class HelloWorld(App):

    def compose(self) -> ComposeResult:
        self.close_button = Button("Shut", id="shut")
        yield Label("Hi there Textual")
        yield self.close_button

    def on_mount(self) -> None:
        self.display.types.background = "darkblue"
        self.close_button.types.background = "crimson"

    def on_button_pressed(self, occasion: Button.Pressed) -> None:
        self.exit(occasion.button.id)

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

The primary change you’ll encounter is that you’re now importing a Button along with your Label.

The following change is that you’re assigning the Button to self.close_button in your compose() perform earlier than yielding the button. By assigning the button to a category variable or attribute, you may extra simply entry it later to vary some options across the widget.

The on_mount() technique is known as when your software enters software mode. Right here you set the background of your app (the display) to “darkblue” and also you set the background coloration of the shut button to “crimson”.

Lastly, you create an on_button_pressed() technique, which is your occasion handler for catching when a button is pressed. When the shut button is pressed, the on_button_pressed()  is known as and your software exits. You cross within the button’s id to inform the appliance which button was used to shut it, though you don’t use that info right here.

It’s time to attempt working your code! If you do, it’s best to see the next:

Hello Textual with close button

Up to now so good. Your software is wanting nice!

Now you’re able to study the fundamentals of styling your software with CSS.

Including Type with CSS

Textual allow you to apply a method utilizing Cascading Type Sheet (CSS) in a lot the identical method that net builders use CSS. You write the CSS file in a separate file that ends with the next extension: .css

By separating out the model from the logic, you may comply with the Mannequin-View-Controller design sample. However even should you don’t comply with that sample, it allows you to separate the logic from the design and may make iterating in your design simpler.

To get began, you’ll first replace your Python file in order that it makes use of a CSS file. Open up your Python editor and create a brand new file named hello_textual_css.py, then enter the next code into it:

# hello_textual_css.py

from textual.app import App, ComposeResult
from textual.widgets import Button, Label


class HelloWorld(App):
    CSS_PATH = "hey.css"

    def compose(self) -> ComposeResult:
        self.close_button = Button("Shut", id="shut")
        yield Label("Hi there Textual", id="hey")
        yield self.close_button

    def on_mount(self) -> None:
        self.display.types.background = "darkblue"
        self.close_button.types.background = "crimson"

    def on_button_pressed(self, occasion: Button.Pressed) -> None:
        self.exit(occasion.button.id)

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

The one change right here is so as to add the category attribute, CSS_PATH, proper after your HelloWorld() class definition. The CSS_PATH could be a relative or absolute path to your CSS file.

Within the instance code above, you employ a relative path to a file named hey.css which ought to be saved in the identical folder as your Python file.

Now you can create hey.css in your Python or textual content editor. Then enter the next code into it:

Display {
    structure: grid;
    grid-size: 2;
    grid-gutter: 2;
    padding: 2;
}
#hey {
    width: 100%;
    peak: 100%;
    column-span: 2;
    content-align: middle backside;
    text-style: daring;
}

Button {
    width: 100%;
    column-span: 2;
}

The Display talked about right here maps to the self.display object in your code. You’re telling Textual that you simply wish to use a grid structure the place the quantity two signifies that the grid will likely be two columns broad and embody two rows.

The spacing between rows is managed by the grid-gutter. Lastly, you set padding so as to add spacing across the content material of the widget itself.

The #hey tag matches to the hey id of a widget in your code. On this case, your Label has the id of “hey”. So all the pieces within the curly braces that follows the #hey tag controls the model of your Label. You need the label to span throughout each columns, and the text-style to be daring. You additionally set the width and peak to 100%.

Lastly, you may have some styling so as to add to Button widgets. There’s just one right here, however this might apply to all buttons should you had extra ones. You’re setting the width of the button to 100% and telling it to span each columns.

Now that the reason is out of the best way, you might be able to attempt working your code. If you do, it’s best to get one thing like this:

Hello Textual with CSS applied

The button is now good and huge, however you may actually make the textual content of the label a bit larger. You must try to determine how to try this as a stretch objective!

Wrapping Up

Textual is superb! The demo has many extra examples than what is roofed right here as does the Textual documentation

Here’s what you discovered from this text:

  • The Textual Demo
  • Making a Label
  • Including a button
  • Utilizing a structure
  • Styling with CSS

This text barely scratches the floor of all of the superb options that Textual has to supply. Regulate this web site although, as there are heaps extra articles on Textual coming quickly!

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments