Rust 初学者指南:用 egui+eframe 开发 Windows 时钟应用

学习笔记作者:admin日期:2025-05-27点击:30

摘要:本文介绍如何使用 Rust 和 egui+eframe 框架快速构建一个 Windows 桌面时钟应用,并详细说明了从环境搭建到代码实现的全过程。

Rust 初学者指南:用 egui+eframe 开发 Windows 时钟应用

一、技术栈

  • 编程语言:Rust
  • GUI 框架:egui + eframe
  • IDE:VSCode
  • 构建系统:Cargo
  • 示例功能:实时更新的时钟应用

二、环境搭建步骤

  1. 安装 Rust 工具链:
    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
  2. 安装 VSCode 插件:Rust Analyzer、CodeLLDB、crates、Toml语言支持。
  3. 配置 VSCode 调试环境:
  4. {
      "version": "0.2.0",
      "configurations": [
        {
          "type": "lldb",
          "request": "launch",
          "name": "Debug executable 'hello'",
          "cargo": "run",
          "args": [],
          "cwd": "${workspaceFolder}"
        }
      ]
    }

三、时钟应用代码实现

      以下是完整的 main.rs 代码:

use eframe::egui;
use std::time::{SystemTime, UNIX_EPOCH};

fn main() -> Result<, eframe::Error> {
    let options = eframe::NativeOptions::default();
    eframe::run_native(
        "我的时钟 App",
        options,
        Box::new(|_cc| Box::new(MyClockApp::new())),
    )
}

struct MyClockApp {
    current_time: String,
}

impl MyClockApp {
    fn new() -> Self {
        Self {
            current_time: get_current_time(),
        }
    }
}

impl eframe::App for MyClockApp {
    fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
        // 每秒更新一次时间
        if ctx.input().time.round() as u64 % 1 == 0 {
            self.current_time = get_current_time();
        }

        egui::CentralPanel::default().show(ctx, |ui| {
            ui.heading("⏰ 当前时间");
            ui.label(&self.current_time);
        });
    }
}

fn get_current_time() -> String {
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap();
    let seconds = now.as_secs();
    chrono::NaiveDateTime::from_timestamp_opt(seconds as i64, 0)
        .map(|t| t.format("%Y-%m-%d %H:%M:%S").to_string())
        .unwrap_or_default()
}

四、运行效果

      运行后,窗口将显示当前时间,并每秒自动更新。

五、后续建议

  • 学习更多 egui 控件功能。
  • 尝试异步编程提升性能。
  • 使用 cargo-wix 或 cargo-bundle 打包应用。

上一篇      下一篇