Exploring Python Text‑Based UI Frameworks: Curses, npyscreen, and Urwid
This article introduces three popular Python libraries for building text‑based terminal user interfaces—Curses, npyscreen, and Urwid—explaining their features, installation steps, key code examples, and practical tips for creating interactive command‑line applications.
In this tutorial the author reviews several common Python libraries for creating text‑based terminal user interfaces, demonstrating how they can be used to build interactive command‑line programs.
Curses
Curses is a dynamic library that provides full‑screen text window capabilities, allowing developers to use the entire screen, create and manage windows, display eight colors, support mouse input, and handle function keys. It runs on any Unix/Linux system that follows the ANSI/POSIX standard and can also be used on Windows after installing the windows-curses package.
<code>pip install windows-curses</code>A simple example shows how to initialize the screen, draw a border, add a string, refresh, wait for a key press, and then clean up:
<code>import curses
myscreen = curses.initscr()
myscreen.border(0)
myscreen.addstr(12, 25, "Python curses in action!")
myscreen.refresh()
myscreen.getch()
curses.endwin()</code>Key points: addstr uses character coordinates, getch blocks until a key is pressed, and curses.endwin() exits the window. For continuous interaction a loop with getch() is required.
Npyscreen
Npyscreen builds on top of Curses to provide a higher‑level, component‑based UI framework. It offers ready‑made widgets such as Form, TitleText, TitleDateCombo, MultiLineEdit, TitleSelectOne, TitleSlider, and more, automatically adapting to screen size.
<code>import npyscreen
class TestApp(npyscreen.NPSApp):
def main(self):
F = npyscreen.Form(name="Welcome to Npyscreen")
t = F.add(npyscreen.TitleText, name="Text:")
fn = F.add(npyscreen.TitleFilename, name="Filename:")
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!
Mutiline text, press ^R to reformat.
""", max_height=5, rely=9)
ms = F.add(npyscreen.TitleSelectOne, max_height=4, name="Pick One", values=["Option1","Option2","Option3"], scroll_exit=True)
ms2 = F.add(npyscreen.TitleMultiSelect, max_height=-2, name="Pick Several", values=["Option1","Option2","Option3"], scroll_exit=True)
F.edit()
print(ms.get_selected_objects())
if __name__ == "__main__":
App = TestApp()
App.run()
</code>To use Npyscreen, install it via pip install npyscreen , subclass npyscreen.NPSApp , implement a main method that creates a Form and adds widgets, then call Form.edit() to hand control to the user.
Urwid
Urwid is a more heavyweight, object‑oriented framework for terminal UIs. It supports window resizing, automatic text alignment, a rich set of pre‑built widgets (edit boxes, buttons, checkboxes, etc.), multiple display modes (native, Curses, LCD, network), UTF‑8/CJK characters, and many colors. It can integrate with event‑driven libraries such as Twisted, Glib, and Tornado.
<code>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()
</code>The example creates a simple screen that displays "Hello World" and shows the pressed key; pressing q or Q exits the program. Note that Urwid runs only on Linux because it depends on Unix‑specific terminal capabilities.
Conclusion
The article showcases three text‑based UI frameworks—Curses, npyscreen, and Urwid—demonstrating that even though graphical interfaces dominate, terminal UIs remain valuable for certain domains and can provide rich, interactive experiences. It also mentions other tools such as prompt_toolkit and a fun example, NetEase‑MusicBox, built with Curses.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.