
1、Python内置了curses库,但是对于Windows操作系统需要安装一个补丁以进行适配。
Windows 下安装补全包:
1 | pip install windows-curses
|
使用说明
2、curses是一个应用广泛的图形函数库,可以在终端内绘制简单的用户界面。
实例
Python内置了curses 库,其使用方法非常简单,以下脚本可以显示出当前按键对应编号:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | # 导入必须的库
import curses
import time
# 初始化命令行界面,返回的 stdscr 为窗口对象,表示命令行界面
stdscr = curses.initscr()
# 使用 noecho 方法关闭命令行回显
curses.noecho()
# 使用 nodelay(True) 方法让 getch 为非阻塞等待(即使没有输入程序也能继续执行)
stdscr.nodelay(True)
while True:
# 清除 stdscr 窗口的内容(清除残留的符号)
stdscr.erase()
# 获取用户输入并放回对应按键的编号
# 非阻塞等待模式下没有输入则返回 -1
key = stdscr.getch()
# 在 stdscr 的第一行第三列显示文字
stdscr.addstr(1, 3, "Hello GitHub." )
# 在 stdscr 的第二行第三列显示文字
stdscr.addstr(2, 3, "Key: %d" % key)
# 刷新窗口,让刚才的 addstr 生效
stdscr.refresh()
# 等待 0.1s 给用户足够反应时间查看文字
time.sleep(0.1)
|
以上就是Python curses库的使用,希望对大家有所帮助。更多Python学习指路:python基础教程
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。