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

 更新时间:2024年02月01日 09:48:41   作者:菲宇 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 使用 Rich 来渲染富文本,所以 Rich 可以渲染的任何东西都可以在 Textual 中使用。
  • Textual 的事件处理是异步的(使用 async 和 await 关键字)。Widgets(UI 组件)可以独立地更新,并通过消息传递相互沟通。
  • Textual 与现代 Web 开发有更多的共同点,布局是用 CSS 完成的,主题可以用 CSS 定制。其他技术是借用了 JS 框架,如 Vue 和 Reactive。

安装 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库的资料请关注脚本之家其它相关文章!

相关文章

  • Docker如何部署Python项目的实现详解

    Docker如何部署Python项目的实现详解

    这篇文章主要介绍了Docker如何部署Python项目的实现详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-10-10
  • 新手入门学习python Numpy基础操作

    新手入门学习python Numpy基础操作

    这篇文章主要介绍了新手入门学习python Numpy基础操作,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-03-03
  • Python 实现取多维数组第n维的前几位

    Python 实现取多维数组第n维的前几位

    今天小编就为大家分享一篇Python 实现取多维数组第n维的前几位,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-11-11
  • 使用Python的PEAK来适配协议的教程

    使用Python的PEAK来适配协议的教程

    这篇文章主要介绍了使用Python的PEAK来适配协议的教程,来自于IBM官方网站技术文档,需要的朋友可以参考下
    2015-04-04
  • Keras实现Vision Transformer VIT模型示例详解

    Keras实现Vision Transformer VIT模型示例详解

    这篇文章主要为大家介绍了Keras实现Vision Transformer VIT模型示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-05-05
  • python单例模式获取IP代理的方法详解

    python单例模式获取IP代理的方法详解

    在使用python对网页进程访问时,以防被禁止,可用使用代理IP的方法减少被禁的可能,下面这篇文章主要给大家介绍了关于python单例模式获取IP代理的相关资料,需要的朋友可以参考借鉴,下面来一起看看吧
    2018-09-09
  • 基于Tensorflow高阶读写教程

    基于Tensorflow高阶读写教程

    今天小编就为大家分享一篇基于Tensorflow高阶读写教程,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-02-02
  • python 特殊属性及方法详细解析

    python 特殊属性及方法详细解析

    这篇文章主要介绍了python 特殊属性及方法详细解析,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-07-07
  • 详解用Python调用百度地图正/逆地理编码API

    详解用Python调用百度地图正/逆地理编码API

    这篇文章主要介绍了详解用Python调用百度地图正/逆地理编码API,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-07-07
  • Python字符串逐字符或逐词反转方法

    Python字符串逐字符或逐词反转方法

    这篇文章主要介绍了Python字符串逐字符或逐词反转方法,本文对逐字符或逐词分别给出两种方法,需要的朋友可以参考下
    2015-05-05

最新评论