python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python Textual库

Python Textual文本用户界面库使用原理探索

作者:菲宇 Python与Django学习

这篇文章主要为大家介绍了Python Textual文本用户界面框架使用原理探索,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

Python Textual文本用户界面库

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

Textual 可在 Linux、macOS 和 Windows 上运行。

Textual 需要 Python 3.7 或更高版本。

Textual 原理

安装 Textual

pip install textual

如果计划开发文本应用,还应使用以下命令安装开发工具:

pip install textual-dev

安装 Textual 后,运行以下命令以了解它的功能:

python -m 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
}

运行效果

其他示例可以参考github

参考文档:

项目github: https://github.com/Textualize/textual 

官网文档: https://textual.textualize.io/ 

以上就是Python Textual文本用户界面库使用原理探索的详细内容,更多关于Python Textual库的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文