Reprinted from: python column Today, I will sort out several common text terminal-based UI frameworks and take a look! 1Curses The first one to appear is Curses. Curses is a dynamic library that provides text-based terminal window functionality. It can: use the entire screen to c

Reprinted from: python column

Today I will sort out several common UI frameworks based on text terminals and take a look!

Curses

The first thing to appear is Curses.

Curses is a dynamic library that provides text-based terminal window functionality. It can:

  • use the entire screen

  • create and manage a window

  • use 8 different colors

  • provide mouse support for programs

  • use the keyboard Function keys

Curses can be found in Runs on any Unix/Linux system that follows ANSI/POSIX standards. It can also run on Windows, but you need to install the windows-curses library additionally:

pipinstallwindows-curses

The picture above is a Tetris game written by a buddy using Curses. It is not full of memories. It can be used to resurrect antique machines.

Let’s also try our best:

importcurses

myscreen=curses.initscr()myscreen.border(0)myscreen.addstr(12,25,"Pythoncursesinaction!")myscreen.refresh()myscreen.getch()curses.endwin( )
  • needs to pay attention to addstr. The first two parameters are character coordinates, not pixel coordinates.

  • getch will block the program until waiting for keyboard input

  • curses.endwin(). The function is to exit the window

  • . If you need to continuously monitor user interaction, you need to write a loop and The input obtained by getch() is used to judge the

code. The running effect is as follows:

Curses is very lightweight, especially suitable for handling simple interactions and replacing complex parameter input programs. It is elegant and simple, and Curses is also the basis of other text terminal UIs. Npyscreen

Npyscreen

is also a Python component library for writing text terminals. It is an application framework built based on Curses.

Compared with Curses, Npyscreen is closer to UI programming. UI display and interaction are completed through the combination of components, and Npyscreen can adapt to screen changes.

Npyscreen provides multiple controls, such as form (Form), single-line text input box (TitleText), date control (TitleDateCombo), multi-line text input box (MultiLineEdit), single-select list (TitleSelectOne), progress bar (TitleSlider), etc. kind of control.

provides powerful functions to meet the requirements of rapid program development, whether it is a simple single-page program or a complex multi-page application.

Let’s look at a small example:

importnpyscreen

classTestApp(npyscreen.NPSApp):defmain(self):#Theselinescreatetheformandpopulateitwithwidgets.#Afairlycomplexscreeninonly8orsolinesofcode-alineforeachcontrol.F=npyscreen.Form(name="WelcometoNpyscreen" ,)t=F.add( npyscreen.TitleText,name="Text:",)fn=F.add(npyscreen.TitleFilename,name="Filename:")fn2=F.add(npyscreen.TitleFilenameCombo,name="Filename2:" )dt=F.add(npyscreen.TitleDateCombo,name="Date:")s=F.add(npyscreen.TitleSlider,out_of=12,name="Slider")ml=F.add(npyscreen .MultiLineEdit,value="""trytypinghere! Mutilinetext,press^Rtoreformat. """,max_height=5,rely=9)ms=F.add(npyscreen.TitleSelectOne,max_height=4,value=[1,] ,name="PickOne",values=["Option1","Option2","Option3"],scroll_exit=True)ms2=F.add(npyscreen.TitleMultiSelect,max_height=-2, value=[1,],name="PickSeveral",values=["Option1","Option2","Option3"],scroll_exit=True)#ThisletstheuserinteractwiththeForm.F.edit() print(ms.get_selected_objects())if__name__=="__main__":App=TestApp()App.run()
  • introduces the Npyscreen module. If not, you can install it through pip: pip install npyscreen

  • inherit npyscreen.NPSApp and create an application class. TestApp

  • implements the main method. In the method, a Form form object is created, then various controls are added to the form object, and some properties of the controls are set.

  • calls the Edit method of the form object and hands over the operation rights to the user.

  • is instantiated at runtime. TestAPP, and then call the run method to start the application, the application will enter the state of waiting for user interaction

The effect of running the above code is as follows:

  • [Tab] / [Shift + Tab] is used to switch the control focus

  • [Enter] / [Space] Used to enter selection, settings, and confirmation

  • In the selection frame, the direction keys operate similarly to vim[4], that is, using hjkl to control

. Doesn’t it feel amazing? It turns out that you can do so many complicated operations with text. I have used commands before. Is the confusion about the progress display in the line clearer~

Urwid

If Curses and Npysreen are lightweight text terminal UI frameworks, then Urwid can definitely be called a heavyweight player.

Urwid contains many features for developing text UI, such as:

  • Application window adaptive

  • Automatic text alignment

  • Easily set text blocks

  • Powerful selection box control

  • can be integrated with various event-driven frameworks, such as Twisted, Glib, Tornado, etc.

  • provides a variety of prefabricated controls such as edit boxes, buttons, multiple (single) selection boxes, etc.

  • display mode supports native, Curses mode, LCD display and network display

  • supports UTF-8 and CJK character sets (can display Chinese )

  • supports multiple colors

Check out the effect:

I don’t know how you feel after reading it. My feeling is: This is too complicated~

can do almost everything under the GUI!

What's even more powerful is that Urwid is a framework built entirely based on object-oriented thinking:

Now let's give it a try and feel the power of Urwid:

importurwid

defshow_or_exit(key):ifkeyin('q','Q' ):raiseurwid.ExitMainLoop()txt.set_text(repr(key))txt=urwid.Text(uhtl2"HelloWorld")fill=urwid.Filler(txt,'middle')loop=urwid.MainLoop(fill , unhandled_input=show_or_exit)loop.run()
  • first introduces the urwid module

  • and defines an input event processing method show_or_exit

  • . In the processing method, when the input key is q or Q, exit the main loop, otherwise the key name will be displayed

  • urwid.Text It is a text control that accepts a string as the display information

  • urwid.Filler is similar to panel, fill the txt control on it, and set the position in the center of the window

  • urwid.MainLoop Set the main loop of Urwid, use fill as the drawing entry of the control, and parameter unhandled_input Accept a key event processing method and use the previously defined show_or_exit

  • loop.run() to start the UI and monitor various events

. When you run this code, you can see that the command line is set to interactive mode, and when the key is pressed, it will be in the center of the window. The key name is displayed, and if the q key is pressed, the program will exit.

Note: Urwid can only run on the Linux operating system. It will not run on Windows due to missing necessary components.

Summary

Due to space limitations, only three text terminal frameworks are shown here, but you can already feel the power of the text terminal-based UI framework. One or two.

also has some excellent frameworks, such as prompt_toolkit. Interested students can study it.

Although text terminal-based UI is no longer mainstream, it still has its value in some special industries or businesses. If you study it, it may be able to help us in special places.

Finally, I recommend a very interesting text terminal-based application - command line NetEase Cloud Music:

is developed based on Curses. If you run it, you will be shocked by its power. You can play it when you have time and compare it!