环境
- Time 2022-08-08
- Rust 1.62.0
- Tui 0.18.0
前言
说明
参考:https://docs.rs/tui/latest/tui/index.html
目标
使用 tui-rs
和 crossterm
启动一个控制台的终端界面。
Cargo.toml
[package]
edition = "2021"
name = "game"
version = "0.1.0"
[dependencies]
anyhow = "*"
crossterm = "*"
tui = "*"
使用 crossterm 作为后端
use std::io;
use tui::{backend::CrosstermBackend, Terminal};
fn main() -> Result<(), io::Error> {
let backend = CrosstermBackend::new(io::stdout());
let _terminal = Terminal::new(backend)?;
Ok(())
}
初始化终端
terminal::enable_raw_mode()?;
let mut backend = CrosstermBackend::new(std::io::stdout());
backend
.execute(terminal::EnterAlternateScreen)?
.execute(terminal::Clear(terminal::ClearType::All))?
.hide_cursor()?;
let mut terminal = tui::Terminal::new(backend)?;
还原终端
terminal::disable_raw_mode()?;
terminal
.backend_mut()
.execute(terminal::Clear(terminal::ClearType::All))?
.execute(terminal::LeaveAlternateScreen)?
.show_cursor()
.context("重置控制台失败")
终端显示方块
terminal.draw(|f| {
let block = widgets::Block::default()
.borders(widgets::Borders::ALL)
.title("控制台方块");
f.render_widget(block, f.size());
})?;
总结
使用 tui-rs
创建了一个终端程序,并且在终端中正常显示一个方块。
附录
源码
use anyhow::{Context, Result};
use crossterm::{terminal, ExecutableCommand};
use tui::backend::{Backend, CrosstermBackend};
use tui::widgets;
pub fn main() -> Result<()> {
terminal::enable_raw_mode()?;
let mut backend = CrosstermBackend::new(std::io::stdout());
backend
.execute(terminal::EnterAlternateScreen)?
.execute(terminal::Clear(terminal::ClearType::All))?
.hide_cursor()?;
let mut terminal = tui::Terminal::new(backend)?;
terminal.draw(|f| {
let block = widgets::Block::default()
.borders(widgets::Borders::ALL)
.title("控制台方块");
f.render_widget(block, f.size());
})?;
std::thread::sleep(std::time::Duration::from_secs(4));
terminal::disable_raw_mode()?;
terminal
.backend_mut()
.execute(terminal::Clear(terminal::ClearType::All))?
.execute(terminal::LeaveAlternateScreen)?
.show_cursor()
.context("重置控制台失败")
}
标签:0049,execute,Tui,terminal,tui,let,控制台,backend
From: https://www.cnblogs.com/jiangbo4444/p/16746034.html