https://github.com/bad-day/TelegramTUI

Create TUI on Python

In this article I will talk about the npyscreen — library for creating console applications.

Install

The package is available for download on PyPI.

sudo pip3 install npyscreen

Object types

Npyscreen uses 3 basic types of objects:

  • Application objects — provide start and end of the application, create forms, process events.
    Basically used NPSAppManaged and StandardApp (with event support).
  • Form objects is the area of the screen that contains widgets.
    Main forms:
    - FormBaseNew — Empty forms.
    - Form — Form with the button «ok».
    - ActionForm — Form with two buttons: “ok” and “cancel”.
    - FormWithMenus — Form that supports the menu.
  • Widget Objects contains various elements located on the forms
    Some widgets:
    - Textfield, PasswordEntry, MultiLineEdit, FilenameCombo —Input forms.
    - DateCombo, ComboBox, FilenameCombo — Drop-down lists.
    - MultiSelect, MultiSelect, BufferPager — Picking Options.
    - Slider, TitleSlider —Sliders.

More information can be found on the official website with the documentation.

Hello world

The best way to create forms is to inherit them from default classes.
You can override the default methods to extend the functionality of the application.

Elements location

By default, widgets use the maximum possible space. 
To use custom coordinates, you need to change the parameters:

  • relx, rely — the position of the widget relative to the origin of the form.
  • width, height, max_width, max_height — limit of the widget size.

Boxes and custom highlightings

To make a wrapper in the form of boxing is simple —you need create a class inherited from BoxTitle and to override the attribute _contained_widget, putting their the widget that will be inside.
There are several default color themes available in npyscreen. If you want, you can add your own. You can install them using the setTheme method.
Customize text highlighting is not so simple. I expanded the functionality of the library to make it work.

Events and Handlers

The StandardApp class in npyscreen supports the event queue.
For the keypress handlers used add_handlers method.

Links

Official documentation.
Official source code
Telegram client written on npyscreen (Which is on the first screenshot).
Updated with me repository (the main repository does not contributing).