从rs GTK中的GTK::Entry获取输入



首先,我对锈蚀非常陌生,而且在GTK 上完全是新的

我想打印";输入";按下按钮时

我该怎么做?

代码:

extern crate gtk;
extern crate gio;
use gtk::prelude::*;
use gio::prelude::*;
use gtk::{Application, ApplicationWindow, Button};
fn main() {
let application = Application::new(
Some("com.github.gtk-rs.examples.basic"),
Default::default(),
).expect("Failed :(");
application.connect_activate(|app| {
let window = ApplicationWindow::new(app);
window.set_title("Title");
window.set_default_size(350, 70);
let win_title = gtk::Label::new(None);
win_title.set_markup("Cool title here");
let Input = gtk::Entry::new();
let row = gtk::Box::new(gtk::Orientation::Vertical, 5);
row.add(&win_title);
row.add(&Input);
let button = Button::with_label("Click me!");
button.connect_clicked(|_| {
println!("This should be the contents of Input");
});
row.add(&button);
window.add(&row);
window.show_all();
});
application.run(&[]);
}```

您就快到了。

您可以使用input.get_text()Entry获取文本。然后,您还需要使用move关键字来允许您的闭包获得条目的所有权。

请注意,我将变量名Input更改为小写(snake_case(,因为这是Rust中建议的样式。

以下是基于您的代码的更新示例:

use gtk::prelude::*;
use gio::prelude::*;
use gtk::{Application, ApplicationWindow, Button};
fn main() {
let application = Application::new(
Some("com.github.gtk-rs.examples.basic"),
Default::default(),
).expect("Failed :(");
application.connect_activate(|app| {
let window = ApplicationWindow::new(app);
window.set_title("Title");
window.set_default_size(350, 70);
let win_title = gtk::Label::new(None);
win_title.set_markup("Cool title here");
let input = gtk::Entry::new();
let row = gtk::Box::new(gtk::Orientation::Vertical, 5);
row.add(&win_title);
row.add(&input);
let button = Button::with_label("Click me!");
button.connect_clicked(move |_| {
println!("{}", input.get_text());
});
row.add(&button);
window.add(&row);
window.show_all();
});
application.run(&[]);
}

最新更新