Easy simple fast create gtk gui calculator rust
⚓ Rust 📅 2025-09-01 👤 surdeus 👁️ 10cargo new calculator
cd calculator
2. * `Cargo.toml`.
```toml
[dependencies]
gtk = "0.9.0"
regl = "0.2.1"
glib = "0.9.0"
-
**
use gtk::prelude::*;
use gtk::{Button, Entry, Grid, Label, Window, WindowType};
use std::ops::Add;struct Calculator {
entry: Entry,
operator: Option,
first_operand: Option,
}impl Calculator {
fn new() -> Self {
let entry = Entry::new();
entry.set_editable(false);Self { entry, operator: None, first_operand: None, } } fn add_button(&self, grid: &Grid, label: &str, row: usize, col: usize) { let button = Button::with_label(label); let entry = self.entry.clone(); button.connect_clicked(move |_| { entry.set_text(&label); }); grid.attach(&button, col as i32, row as i32, 1, 1); } fn add_operations(&mut self, grid: &Grid) { let calc_op = |operator, entry: &Entry, first_operand: &mut Option<f64>| { let current_text = entry.get_text().unwrap(); if let Ok(value) = current_text.parse::<f64>() { *first_operand = Some(value); entry.set_text(&operator); } }; let operator_buttons = vec![("+", "add"), ("-", "sub"), ("*", "mul"), ("/", "div")]; for (index, (label, op)) in operator_buttons.iter().enumerate() { let entry = self.entry.clone(); let first_operand = &mut self.first_operand; let button = Button::with_label(label); button.connect_clicked(move |_| { calc_op(op, &entry, first_operand); }); grid.attach(&button, index as i32, 5, 1, 1); } }}
fn main() {
gtk::init().expect("Failed to initialize GTK.");let window = Window::new(WindowType::Toplevel); window.set_title("Calculator"); window.set_default_size(200, 200); let grid = Grid::new(); let calculator = Calculator::new(); grid.attach(&calculator.entry, 0, 0, 4, 1); let buttons = [ "7", "8", "9", "4", "5", "6", "1", "2", "3", "0", "+", "=", ]; for (index, label) in buttons.iter().enumerate() { calculator.add_button(&grid, label, (index / 3) + 1, index % 3); } window.add(&grid); window.connect_delete_event(|_, _| { gtk::main_quit(); Inhibit(false) }); window.show_all(); gtk::main();}
-
**
cargo run
2 posts - 2 participants
🏷️ Rust_feed