如何从按钮单击条目中获取信息? [英] How do I get information from an entry on button click?

查看:81
本文介绍了如何从按钮单击条目中获取信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从按钮单击的条目中获取输入,并在单击另一个按钮时显示该信息.这给我一个错误,因为闭包拥有我要在其中存储信息的firstname变量的所有权.

I want to get an input from an entry on a button click and display that information when another button is clicked. This gives me an error because the closure takes ownership of my firstname variable, in which I want to store the information.

如何从条目中获取信息并重复使用?

How do I get the information out of the entry and reuse it?

// import gtk libs
extern crate gio;
extern crate gtk;

// declare use of gtk
use gtk::prelude::*;

fn main() {
    let mut firstname = String::new();

    if gtk::init().is_err() {
        println!("Failed to initialize GTK.");
        return;
    }
    let glade_src = include_str!("builder.glade");
    let builder = gtk::Builder::new_from_string(glade_src);

    let window: gtk::Window = builder.get_object("window1").unwrap();
    let buttonSubmit: gtk::Button = builder.get_object("buttonSubmit").unwrap();
    let buttonShow: gtk::Button = builder.get_object("buttonShow").unwrap();
    let entryFirstname: gtk::Entry = builder.get_object("entryFirstname").unwrap();

    // get information from entry
    buttonSubmit.connect_clicked(move |_| {
        firstname = entryFirstname.get_buffer().get_text();
    });

    // output information
    let firstname_clone = firstname.clone();
    buttonShow.connect_clicked(move |_| {
        println!("Firstname: {}", firstname_clone);
    });

    window.show_all();

    gtk::main();
}

推荐答案

一旦您的字符串已在闭包内移动,编译器将无法再静态检查您是否不在混合对其的读写访问.您需要使用 RefCell 来启用运行时选择的读写访问权限,可能与 Rc 结合使用用于适当的内存管理:

Once your string has been moved inside the closures, the compiler can no longer check statically that your are not mixing read and write accesses to it. You need to use a RefCell to enable runtime selection of read/write accesses, probably combined with Rc for proper memory management:

let firstname = Rc::new(RefCell::new(String::new()));
let firstname_clone = firstname.clone();
// ...
buttonSubmit.connect_clicked(move |_| {
    firstname.replace(entryFirstname.get_buffer().get_text());
});
// ...
buttonShow.connect_clicked(move |_| {
    println!("Firstname: {}", firstname_clone.borrow());
});

这篇关于如何从按钮单击条目中获取信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆