[1337]python文本终端GUI框架Textual

220 阅读3分钟

@[toc]

github:github.com/Textualize/…

Textual是一个用于 Python 的 TUI(文本用户界面)库,是 Rich 的姐妹项目,也依赖于 Rich。它支持 Rich 的 Renderable 类,同时有自己的互动性组件 Widget 类。通过使用简单的 Python API 构建复杂的用户界面,在shell工具或浏览器上运行。

Textual 可在 Linux、macOS 和 Windows 上运行。需要 Python 3.8 或更高版本。

Textual 原理

  • Textual 使用 Rich 来渲染富文本,所以 Rich 可以渲染的任何东西都可以在 Textual 中使用。
  • Textual 的事件处理是异步的(使用 async 和 await 关键字)。Widgets(UI 组件)可以独立地更新,并通过消息传递相互沟通。
  • Textual 与现代 Web 开发有更多的共同点,布局是用 CSS 完成的,主题可以用 CSS 定制。其他技术是借用了 JS 框架,如 Vue 和 Reactive。

安装与入门

安装Textual非常简单,只需要使用pip命令即可完成:

pip install textual textual-dev

textual-dev 包含了开发过程中所需的额外工具。 官方文档提供了详尽的入门指南和教程,即使是从未接触过Textual的开发者也能快速上手,轻松构建自己的第一个Textual应用。 此外,你可以通过运行 python -m textual 来体验Textual 的功能演示,或者使用 uvx --python 3.12 textual-demo (需要安装uv) 来运行演示程序,快速感受Textual 的魅力。

widgets小部件

Button #按钮 Checkbox #复选框 Collapsible #收起/折叠 ContentSwitcher #内容切换器 DataTable #数据表 Digits #数字 DirectoryTree #目录树 Footer #页脚 Header #页眉 Input #输入 Label #标签 ListView #列表 LoadingIndicator #加载指示器 Log #日志 MarkdownViewer #Markdown查看器 Markdown #Markdown OptionList #选项列表 Placeholder #占位符 Pretty #格式化 ProgressBar #进度条 RadioButton #单选按钮 RadioSet #复选按钮 RichLog #rich日志 Rule #分割线 Select #选择 SelectionList #选择列表 Sparkline #柱状图 Static #静态文件 Switch #开关 Tabs TabbedContent选项卡内容 TextArea #文本区域 Tree #树

Textual 使用 CSS 将样式应用于小部件

  • 倒计时示例
from time import monotonic
from textual.app import App, ComposeResult
from textual.containers import ScrollableContainer
from textual.reactive import reactive
from textual.widgets import Button, Footer, Header, Static


class TimeDisplay(Static):
    """A widget to display elapsed time."""
    start_time = reactive(monotonic)
    time = reactive(0.0)
    total = reactive(0.0)
    def on_mount(self) -> None:
        """Event handler called when widget is added to the app."""
        self.update_timer = self.set_interval(1 / 60, self.update_time, pause=True)
    def update_time(self) -> None:
        """Method to update time to current."""
        self.time = self.total + (monotonic() - self.start_time)
    def watch_time(self, time: float) -> None:
        """Called when the time attribute changes."""
        minutes, seconds = divmod(time, 60)
        hours, minutes = divmod(minutes, 60)
        self.update(f"{hours:02,.0f}:{minutes:02.0f}:{seconds:05.2f}")
    def start(self) -> None:
        """Method to start (or resume) time updating."""
        self.start_time = monotonic()
        self.update_timer.resume()
    def stop(self) -> None:
        """Method to stop the time display updating."""
        self.update_timer.pause()
        self.total += monotonic() - self.start_time
        self.time = self.total
    def reset(self) -> None:
        """Method to reset the time display to zero."""
        self.total = 0
        self.time = 0

class Stopwatch(Static):
    """A stopwatch widget."""
    def on_button_pressed(self, event: Button.Pressed) -> None:
        """Event handler called when a button is pressed."""
        button_id = event.button.id
        time_display = self.query_one(TimeDisplay)
        if button_id == "start":
            time_display.start()
            self.add_class("started")
        elif button_id == "stop":
            time_display.stop()
            self.remove_class("started")
        elif button_id == "reset":
            time_display.reset()
    def compose(self) -> ComposeResult:
        """Create child widgets of a stopwatch."""
        yield Button("Start", id="start", variant="success")
        yield Button("Stop", id="stop", variant="error")
        yield Button("Reset", id="reset")
        yield TimeDisplay()

class StopwatchApp(App):
    """A Textual app to manage stopwatches."""
    CSS_PATH = "test3.tcss"
    BINDINGS = [("d", "toggle_dark", "Toggle dark mode")]
    def compose(self) -> ComposeResult:
        """Called to add widgets to the app."""
        yield Header()
        yield Footer()
        yield ScrollableContainer(Stopwatch(), Stopwatch(), Stopwatch())
    def action_toggle_dark(self) -> None:
        """An action to toggle dark mode."""
        self.dark = not self.dark


if __name__ == "__main__":
    app = StopwatchApp()
    app.run()
  • css样式
Stopwatch {
    layout: horizontal;
    background: $boost;
    height: 5;
    margin: 1;
    min-width: 50;
    padding: 1;
}
TimeDisplay {
    content-align: center middle;
    text-opacity: 60%;
    height: 3;
}
Button {
    width: 16;
}
#start {
    dock: left;
}
#stop {
    dock: left;
    display: none;
}
#reset {
    dock: right;
}
.started {
    text-style: bold;
    background: $success;
    color: $text;
}
.started TimeDisplay {
    text-opacity: 100%;
}
.started #start {
    display: none
}
.started #stop {
    display: block
}
.started #reset {
    visibility: hidden
}

运行效果