Python命令行UI布局工具terminal-layout如何使用
6 回复
别只收藏呀,来点回复~
terminal-layout 是一个用于在终端中创建复杂UI布局的Python库,它基于 rich 库构建,可以轻松实现分栏、面板、表格等布局。
首先安装它:
pip install terminal-layout
基本使用很简单,这里给你几个实用例子:
1. 基础布局
from terminal_layout import *
# 创建布局容器
container = Container(width=80, height=20)
# 添加一个标题面板
title = TextView('终端UI示例', style='bold red', align='center')
container.add_child(title, size=3) # 占3行高度
# 添加内容区域
content = LinearLayout(orientation='horizontal')
left_panel = TextView('左侧面板\n内容...', style='green')
right_panel = TextView('右侧面板\n更多内容...', style='blue')
content.add_child(left_panel, weight=1)
content.add_child(right_panel, weight=1)
container.add_child(content)
container.render()
2. 表格布局
from terminal_layout import *
from terminal_layout.extensions import TableView
container = Container(width=100, height=30)
# 创建表格
table = TableView(
headers=['ID', '名称', '状态'],
rows=[
['001', '任务A', '运行中'],
['002', '任务B', '已完成'],
['003', '任务C', '等待中']
],
style='cyan'
)
container.add_child(table)
container.render()
3. 动态更新布局
from terminal_layout import *
import time
container = Container()
status = TextView('准备开始...', style='yellow')
container.add_child(status)
for i in range(5):
status.text = f'处理中... ({i+1}/5)'
container.render()
time.sleep(1)
status.text = '处理完成!'
status.style = 'green bold'
container.render()
4. 复杂嵌套布局
from terminal_layout import *
container = Container(width=90, height=25)
# 顶部标题
header = TextView('系统监控面板', style='bold white on_blue', align='center')
container.add_child(header, size=2)
# 主内容区(左右分栏)
main = LinearLayout(orientation='horizontal')
# 左侧统计信息
stats = LinearLayout(orientation='vertical')
stats.add_child(TextView('CPU: 45%', style='green'))
stats.add_child(TextView('内存: 78%', style='yellow'))
stats.add_child(TextView('磁盘: 32%', style='cyan'))
# 右侧日志区域
logs = TextView('系统日志:\n- 服务启动\n- 用户登录\n- 数据备份', style='dim')
main.add_child(stats, weight=1)
main.add_child(logs, weight=2)
container.add_child(main)
container.render()
关键点:
Container是根容器,设置整体尺寸LinearLayout用于线性排列(水平/垂直)TextView显示文本内容size参数指定固定大小,weight参数按比例分配空间- 调用
render()实际输出到终端
这个库适合做CLI工具的状态面板、监控界面或者交互式终端应用。布局用weight参数控制比例比较方便。
建议先跑通基础例子再尝试复杂布局。
有时间模仿这个 golang 版的
倒不如在.bashrc 文件里加几个带颜色的 alias 参数
主要功能不是颜色,而是布局
0.0


