Rust语言使用iced实现简单GUI页面

使用cargo新建一个rust项目

bash 复制代码
cargo new gui_demo
cd gui_demo

编辑Cargo.toml文件 ,添加iced依赖

rust 复制代码
[package]
name = "gui_demo"
version = "0.1.0"
edition = "2021"

[dependencies]
iced = "0.4.2"

编辑src/main.rs文件:

rust 复制代码
use iced::{button, widget::{Button, Column, Text}, Application, Command, Element, Settings, Subscription};
use iced::executor::Default as Executor;

// 定义应用程序的状态
struct RustGuiApp {
    count: i32,
    button_state: button::State,
}

// 定义应用程序的消息类型
#[derive(Debug, Clone, Copy)]
enum Message {
    IncrementPressed,
}

impl Application for RustGuiApp {
    type Executor = Executor;
    type Message = Message;
    type Flags = ();

    fn new(_flags: ()) -> (Self, Command<Self::Message>) {
        (
            RustGuiApp {
                count: 0,
                button_state: button::State::new(),
            },
            Command::none(),
        )
    }
    
    // 设置窗口标题
    fn title(&self) -> String {
        String::from("Rust GUI Example")
    }

    fn update(&mut self, message: Self::Message) -> Command<Self::Message> {
        if let Message::IncrementPressed = message {
            self.count += 1;
        }
        Command::none()
    }

    fn view(&mut self) -> Element<Self::Message> {
        let button = Button::new(&mut self.button_state, Text::new("Increment"))
            .on_press(Message::IncrementPressed);

        //    添加文字和一些你想加的东西
        Column::new()
            .push(Text::new("Hello, Rust GUI!").size(50))
            .push(Text::new(self.count.to_string()).size(50))
            .push(button)
            .into()
    }

    fn subscription(&self) -> Subscription<Self::Message> {
        Subscription::none()
    }
}

fn main() -> iced::Result {
    RustGuiApp::run(Settings::default())
}

最后使用命令运行

bash 复制代码
cargo run

运行效果展示,还是挺不错滴

相关推荐
Dxy123931021617 分钟前
Python线程锁:为什么多线程会“打架“,以及怎么解决
开发语言·前端·python
guygg8829 分钟前
人行走作用下板的振动响应 MATLAB 仿真
开发语言·matlab
小二·1 小时前
Next.js 15 全栈开发实战
开发语言·javascript·ecmascript
fox_lht1 小时前
15.3.改进我们之前的输入、输出项目
开发语言·后端·学习·rust
java1234_小锋1 小时前
LangChain4j 开发Java Agent智能体- 多模态支持
java·开发语言·langchain4j
凡人叶枫1 小时前
Effective C++ 条款23:宁以 non-member、non-friend 替换 member 函数
linux·开发语言·c++·嵌入式开发
张忠琳1 小时前
【Go 1.26.4】Golang Channel 深度解析
开发语言·后端·golang
盈建云系统1 小时前
B2B产品展示网站怎么做?从产品目录到询盘表单,企业获客页面搭建流程
开发语言·网站搭建·开发网站
不会C语言的男孩1 小时前
Linux 系统编程 · 第 4 章:文件属性与元数据
linux·c语言·开发语言
kernelcraft1 小时前
Boto3:Python 操作 AWS 的官方 SDK
开发语言·python·其他·aws