程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python text terminal GUI framework, cool

編輯:Python

Some readers asked : Is there a terminal based on text GUI Development framework ?
Today I will take you , Sort out several common text-based terminals UI frame , Take a glance at it !

Curses

The first thing to show up is Curses[1].

Curse
Curses It is a dynamic library that can provide the function of text-based terminal window , It can :

  • Use the entire screen

  • Create and manage a window

  • Use 8 Different colors

  • Provide mouse support for programs

  • Use the function keys on the keyboard Curses Can be followed at any time ANSI/POSIX The standard Unix/Linux Running on the system .Windows Can also run on , However, additional installation is required windows-curses library :

pip install windows-curses

The picture above , Just a buddy with Curses Written Tetris [2], I don't feel full of memories , You can take it to the resurrection antique machine .
Let's try ox knife :

import cursesmyscreen = curses.initscr()myscreen.border(0)myscreen.addstr(12, 25, "Python curses in action!")myscreen.refresh()myscreen.getch()curses.endwin()
  • We need to pay attention to addstr The first two parameters are character coordinates , Not pixel coordinates

  • getch It blocks 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 , Also on getch() Get the input to judge The code works as follows :

    A profound
    Curses Very lightweight , Especially suitable for dealing with simple interaction , A program that replaces complex parameter input , Both elegant , Simple , and Curses It is also other text terminals UI The basis of .

Npyscreen

Npyscreen[3] It is also a terminal that uses to write text Python Component library , Is based on Curses Build an application framework .
Compared with Curses,Npyscreen Closer to the UI Programming , Through the combination of components UI Presentation and interaction , and Npyscreen Can adapt to screen changes .
Npyscreen Provides multiple controls , such as Forms (Form)、 Single line text input box (TitleText)、 Date control (TitleDateCombo)、 Multiline text input box (MultiLineEdit)、 Single list (TitleSelectOne)、 Progress bar (TitleSlider) And other controls .
Provide powerful functions , Meet the requirements of rapid program development , Whether it's a simple single page program or a complex multi page application .
Let's take a little example :

import npyscreenclass 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()
  • introduce Npyscreen modular , If it doesn't pass pip install : pip install npyscreen

  • Inherit npyscreen.NPSApp Create an application class TestApp

  • Realization main Method , Method to create a Form Form object , Then add various controls to the form object , And set some properties of the control

  • Call the of the form object Edit Method , Give the operation right to the user

  • At run time , Instantiation TestAPP , And then call run Method to start the application , The application can enter the state of waiting for user interaction The effect of the above code is as follows :

    Npyscreen

  • [Tab] / [Shift + Tab] Used to switch control focus

  • [ enter ] / [ Space ] Used to enter and select 、 Set up 、 confirm

  • In the selection frame , Direction keys and vim[4] The operation is similar to , That is, through hjkl To control Is it amazing , You can do so many complicated operations with text , Whether the previous doubts about the progress display in the command line are clear ~

Urwid

if Curses and Npysreen Is a lightweight text terminal UI frame , that Urwid[5] Definitely a heavyweight .
Urwid Contains many development texts UI Characteristics of , for example :

  • Apply window adaptation

  • Automatic text alignment

  • Easily set text blocks

  • Powerful selection box control

  • It can be integrated with various event driven frameworks , For example, Twisted[6], Glib[7], Tornado[8] wait

  • Provide such as edit box 、 Button 、 many ( single ) Check the box And other prefabricated controls

  • The display mode supports native 、Curses Pattern 、LCD display as well as Network display

  • Support UTF-8 as well as CJK Character set ( Can display Chinese )

  • Support multiple colors Look at the effect :

    Message box

    Multi font

    color
    I don't know how you feel after watching it , My feeling is : It's too voluminous ~
    It's almost possible to do GUI Everything under !
    Even worse ,Urwid The framework is completely built according to the idea of object-oriented :

    Urwid chart
    Now let's give it a try , Feel the Urwid A powerful :

import urwiddef 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()
  • First introduced urwid modular

  • Defines an input event handling method show_or_exit

  • In the process , When the input key is q perhaps Q when , Exit the main loop , Otherwise, the key name will be displayed

  • urwid.Text Is a text control , Accept a string as a display message

  • urwid.Filler Be similar to panel, take txt Control is filled on it , The position is set in the center of the window

  • urwid.MainLoop Set up Urwid Main cycle of , take fill As the drawing entry of the control , Parameters unhandled_input Accept a key event handling method , It uses the previously defined show_or_exit

  • loop.run() start-up UI, And monitor various events Run this code , You can see that the command line is set to interactive mode , When pressing the key, the key name will be displayed in the center of the window , If you press q key , The program will exit .

    Be careful
    Urwid Only in Linux Running in the operating system ,Windows Will fail to run due to missing necessary components

summary

Limited to space , Only three text terminal frameworks are shown here , However, it has been able to use text-based terminals UI The powerful feeling of the framework is one or two .
Some frameworks are also excellent , such as prompt_toolkit, Those of you who are interested can study it .
Although text-based terminals UI It is no longer the mainstream , But in some special industries or businesses , It still has its value , Look at the , Maybe it can help us in a special place .
Last , Recommend a very interesting application based on text terminal —— Command line Netease cloud music [9]:

NetEase-MusicBox
Is based on Curses Development , If it runs , Can be shocked by its strength , You can play when you are free , finger heart !
The above is all the content shared this time , If you think the article is good , Welcome to the official account : Python Programming learning circle , Daily dry goods sharing , send out “J” You can also get a lot of learning materials . Or go to Programming learning network , Learn more about programming techniques .
author : Programmer Xiaoliu

Game programming , A game development favorite ~

If the picture is not displayed for a long time , Please use Chrome Kernel browser .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved