Home > Backend Development > Python Tutorial > Python text terminal GUI framework, so cool

Python text terminal GUI framework, so cool

王林
Release: 2023-04-12 12:52:08
forward
1529 people have browsed it

Curses

The first one to appear is Curses[1].

Python text terminal GUI framework, so cool

Curse

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

  • Use the entire Screen
  • Create and manage a window
  • Use 8 different colors
  • Provide mouse support for the program
  • Use the function keys on the keyboard

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

pip install windows-curses
Copy after login

The picture above is a Tetris game written by a buddy using Curses[2]. It doesn’t feel full of memories, so you can take it Go and resurrect antique machines.

Let’s try our best:

import curses
myscreen = curses.initscr()
myscreen.border(0)
myscreen.addstr(12, 25, "Python curses in action!")
myscreen.refresh()
myscreen.getch()
curses.endwin()
Copy after login
  • Please note that the first two parameters of addstr are character coordinates, not pixel coordinates
  • getch will block the program until waiting Keyboard input
  • curses.endwin() is used to exit the window
  • If you need to continuously monitor user interaction, you need to write a loop and judge the input obtained by getch()

The running effect of the code is as follows:

Python text terminal GUI framework, so cool

##a small test

Curses is very lightweight, especially suitable for handling simple interactions and replacing complex parameter inputs The program is both elegant and simple, and Curses is also the basis for other text terminal UIs.

Npyscreen

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

Compared to 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), radio selection list (TitleSelectOne), and progress Bar (TitleSlider) and other controls.

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

Let’s take a look at a small example:

import npyscreen
class TestApp(npyscreen.NPSApp):
def main(self):
# These lines create the form and populate it with widgets.
# A fairly complex screen in only 8 or so lines of code - a line for each control.
F= npyscreen.Form(name = "Welcome to Npyscreen",)
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 = """try typing here!nMutiline text, press ^R to reformat.n""",
 max_height=5, rely=9)
ms = F.add(npyscreen.TitleSelectOne, max_height=4, value = [1,], name="Pick One",
values = ["Option1","Option2","Option3"], scroll_exit=True)
ms2= F.add(npyscreen.TitleMultiSelect, max_height =-2, value = [1,], name="Pick Several",
values = ["Option1","Option2","Option3"], scroll_exit=True)
# This lets the user interact with the Form.
F.edit()
print(ms.get_selected_objects())
if __name__ == "__main__":
App = TestApp()
App.run()
Copy after login

    Introduce the Npyscreen module. If not, you can install it through pip: pip install npyscreen
  • Inherit npyscreen.NPSApp and create an application class. TestApp
  • Implement the main method, create a Form object in the method, then add various controls to the form object, and set some properties of the controls
  • Call the Edit method of the form object to perform the operation The power is given to the user
  • At runtime, instantiate TestAPP, and then call the run method to start the application. The application can then enter a state waiting for user interaction
The effect of the above code is as follows:

Python text terminal GUI framework, so cool

Npyscreen

    [Tab] / [Shift Tab] Used to switch control focus
  • [Enter] / [ Space] is used to enter selection, setting, and confirmation
  • In the selection frame, the direction keys operate similarly to vim[4], that is, controlled by hjkl
Doesn’t it feel magical? , it turns out that you can do so many complex operations with text. Is the previous doubt about the progress display in the command line clearer~

Urwid

If Curses and Npysreen are lightweight Text terminal UI framework, then Urwid[5] can definitely be called a heavyweight player.

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

    Application window adaption
  • Automatic text alignment
  • Easily set text blocks
  • Powerful selection box control
  • Can be integrated with various event-driven frameworks, such as Twisted[6], Glib[7], Tornado[8], 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 set (can display Chinese)
  • Supports multiple colors
Look at the effect:

Python text terminal GUI framework, so cool

Message box

Python text terminal GUI framework, so cool

Multiple fonts

Python text terminal GUI framework, so cool

色彩

不知道你看了是什么感觉,我的感觉是:这也太卷了吧~

几乎可以做 GUI 下的所有事情!

更厉害的是,Urwid 完全是按照面向对象的思想打造的框架:

Python text terminal GUI framework, so cool

Urwid 结构图

现在我们来小试一把,感受一下 Urwid 的强大:

import urwid
def show_or_exit(key):
if key in ('q', 'Q'):
raise urwid.ExitMainLoop()
txt.set_text(repr(key))
txt = urwid.Text(u"Hello World")
fill = urwid.Filler(txt, 'middle')
loop = urwid.MainLoop(fill, unhandled_input=show_or_exit)
loop.run()
Copy after login
  • 先引入 urwid 模块
  • 定义了一个输入事件处理方法 show_or_exit
  • 处理方法中,当输入按键是 q 或者 Q 时,退出主循环,否则将按键名称显示出来
  • urwid.Text 是一个文本控件,接受一个字符串作为显示信息
  • urwid.Filler 类似于 panel,将 txt 控件填充在上面,位置设置在窗口中央
  • urwid.MainLoop 设置 Urwid 的主循环,将 fill 作为控件的绘制入口,参数 unhandled_input 接受一个按键事件处理方法,用的就是前面定义的 show_or_exit
  • loop.run() 启动 UI,并监控各种事件

运行这段代码,就可以看到命令行被设置为交互模式,按键时会在窗口中央显示出键名,如果按下 q 键,程序就会退出。

注意:

Urwid 只能在 Linux 操作系统中运行,Windows 上会因为缺失必要组件无法运行

总结

限于篇幅,这里只展示了三种文本终端框架,不过已经能对基于文本终端 UI 框架的强大感受一二了。

还有一些框架也很优秀,比如 prompt_toolkit,有兴趣的同学可以研究一下。

虽然基于文本终端的 UI 早已不是主流,但是在一些特殊的行业或者业务中,还是有其存在的价值,研究一下,说不定在特殊的地方可以帮助到我们。

最后,推荐一个很有意思的基于文本终端的应用 —— 命令行网易云音乐[9]:

Python text terminal GUI framework, so cool

NetEase-MusicBox

是基于 Curses 开发,如果运行起来,能被它的强悍所震撼,有空可以玩玩,比心!

The above is the detailed content of Python text terminal GUI framework, so cool. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template