Python?Textual文本用戶界面庫(kù)使用原理探索
Python Textual文本用戶界面庫(kù)
Textual是一個(gè)用于 Python 的 TUI(文本用戶界面)庫(kù),是 Rich 的姐妹項(xiàng)目,也依賴于 Rich。它支持 Rich 的 Renderable 類,同時(shí)有自己的互動(dòng)性組件 Widget 類。通過(guò)使用簡(jiǎn)單的 Python API 構(gòu)建復(fù)雜的用戶界面,在shell工具或?yàn)g覽器上運(yùn)行。
Textual 可在 Linux、macOS 和 Windows 上運(yùn)行。
Textual 需要 Python 3.7 或更高版本。
Textual 原理
- Textual 使用 Rich 來(lái)渲染富文本,所以 Rich 可以渲染的任何東西都可以在 Textual 中使用。
- Textual 的事件處理是異步的(使用 async 和 await 關(guān)鍵字)。Widgets(UI 組件)可以獨(dú)立地更新,并通過(guò)消息傳遞相互溝通。
- Textual 與現(xiàn)代 Web 開發(fā)有更多的共同點(diǎn),布局是用 CSS 完成的,主題可以用 CSS 定制。其他技術(shù)是借用了 JS 框架,如 Vue 和 Reactive。
安裝 Textual
pip install textual
如果計(jì)劃開發(fā)文本應(yīng)用,還應(yīng)使用以下命令安裝開發(fā)工具:
pip install textual-dev
安裝 Textual 后,運(yùn)行以下命令以了解它的功能:
python -m textual
運(yùn)行結(jié)果:

widgets小部件
Button #按鈕
Checkbox #復(fù)選框
Collapsible #收起/折疊
ContentSwitcher#內(nèi)容切換器
DataTable#數(shù)據(jù)表
Digits #數(shù)字
DirectoryTree #目錄樹
Footer #頁(yè)腳
Header#頁(yè)眉
Input#輸入
Label#標(biāo)簽
ListView#列表
LoadingIndicator#加載指示器
Log#日志
MarkdownViewer#Markdown查看器
Markdown#Markdown
OptionList#選項(xiàng)列表
Placeholder#占位符
Pretty#格式化
ProgressBar#進(jìn)度條
RadioButton#單選按鈕
RadioSet#復(fù)選按鈕
RichLog#rich日志
Rule#分割線
Select#選擇
SelectionList#選擇列表
Sparkline#柱狀圖
Static#靜態(tài)文件
Switch#開關(guān)
Tabs#
TabbedContent選項(xiàng)卡內(nèi)容
TextArea#文本區(qū)域
Tree#樹
Textual 使用 CSS 將樣式應(yīng)用于小部件
倒計(jì)時(shí)示例
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
}運(yùn)行效果

其他示例可以參考github


參考文檔:
項(xiàng)目github: https://github.com/Textualize/textual
官網(wǎng)文檔: https://textual.textualize.io/
以上就是Python Textual文本用戶界面庫(kù)使用原理探索的詳細(xì)內(nèi)容,更多關(guān)于Python Textual庫(kù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Pyenv uninstall刪除不需要的Python版本的詳細(xì)操作
文章介紹了如何使用pyenv和Miniconda來(lái)管理Python環(huán)境,特別是在清理不再需要的Python版本和環(huán)境時(shí)的實(shí)戰(zhàn)技巧,強(qiáng)調(diào)了pyenv作為Python版本管理器的優(yōu)勢(shì),感興趣的朋友跟隨小編一起看看吧2026-03-03
Python使用requests模塊發(fā)送http請(qǐng)求的方法介紹
Python?Requests是一個(gè)?HTTP?庫(kù),它允許我們向?Web?服務(wù)器發(fā)送??HTTP?請(qǐng)求,并獲取響應(yīng)結(jié)果,本文將會(huì)詳細(xì)介紹Python?requests模塊如何發(fā)送http請(qǐng)求,文中有相關(guān)的代碼示例,需要的朋友可以參考下2023-06-06
python 實(shí)現(xiàn)批量圖片識(shí)別并翻譯
這篇文章主要介紹了python 實(shí)現(xiàn)批量圖片識(shí)別并翻譯,幫助大家利用python處理圖片,感興趣的朋友可以了解下2020-11-11
pyecharts繪制各種數(shù)據(jù)可視化圖表案例附效果+代碼
這篇文章主要介紹了pyecharts繪制各種數(shù)據(jù)可視化圖表案例并附效果和代碼,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,感興趣的小伙伴可以參考一下2022-06-06
Selenium?4.2.0?標(biāo)簽定位8種方法詳解
這篇文章主要介紹了Selenium?4.2.0?標(biāo)簽定位8種方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06
淺談Python對(duì)內(nèi)存的使用(深淺拷貝)
這篇文章主要介紹了淺談Python對(duì)內(nèi)存的使用(深淺拷貝),具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01
pyecharts調(diào)整圖例與各板塊的位置間距實(shí)例
這篇文章主要介紹了pyecharts調(diào)整圖例與各板塊的位置間距實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-05-05
淺析form標(biāo)簽中的GET和POST提交方式區(qū)別
在HTML中,form表單的作用是收集標(biāo)簽中的內(nèi)容<form>...</form> 中間可以由訪問(wèn)者添加類似于文本,選擇,或者一些控制模塊等等.然后這些內(nèi)容將會(huì)被送到服務(wù)端2021-09-09

