我是rust的新手,我正在尝试学习如何在GUI应用程序中使用GTK,但是我不知道如何在应用程序窗口中绘制图像(.png/.jpg)。
extern crate gdk;
extern crate gio;
extern crate gtk;
use gio::prelude::*;
use gtk::prelude::*;
use gtk::{Image, Window, WindowType};
use gdk_pixbuf::{Pixbuf, PixbufLoader};
fn main() {
gtk::init().expect("Failed to initialize GTK.");
let window = Window::new(WindowType::Toplevel);
window.set_title("Image Viewer");
window.set_default_size(400, 400);
let image = Image::new();
let pixbuf_loader = PixbufLoader::new();
pixbuf_loader.write(&std::fs::read("path_to_your_image.png").expect("Failed to read image file"))
.expect("Failed to load image");
pixbuf_loader.close().expect("Failed to close PixbufLoader");
let pixbuf = pixbuf_loader.get_pixbuf().expect("Failed to get Pixbuf");
image.set_from_pixbuf(Some(&pixbuf));
window.add(&image);
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
window.show_all();
gtk::main();
}
字符串
I've tried the code above but I'm unsure how to fix the following errors.
错误:
warning: unused import: `Pixbuf`
--> src/main.rs:8:18
|
8 | use gdk_pixbuf::{Pixbuf, PixbufLoader};
| ^^^^^^
|
= note: `#[warn(unused_imports)]` on by default
error[E0599]: no method named `get_pixbuf` found for struct `PixbufLoader` in the current scope
--> src/main.rs:24:32
|
24 | let pixbuf = pixbuf_loader.get_pixbuf().expect("Failed to get Pixbuf");
| ^^^^^^^^^^ method not found in `PixbufLoader`
error[E0425]: cannot find function, tuple struct or tuple variant `Inhibit` in this scope
--> src/main.rs:32:9
|
32 | Inhibit(false)
| ^^^^^^^ not found in this scope
warning: unused import: `gio::prelude`
--> src/main.rs:5:5
|
5 | use gio::prelude::*;
| ^^^^^^^^^^^^
型
1条答案
按热度按时间bq9c1y661#
目前还不清楚您使用的是哪个GTK版本,所以让我们来看看GTK 3和GTK 4
在GTK 3中,可以使用
gtk::Image::from_file()
从文件名立即创建GtkImage。在GTK 4中,有一个名为
GtkPicture
的小部件,它经过了更好的优化,可以显示任何图像(而不是图标等基本图像)。注意,如果你还在学习,最好不时地看看gtk3-rs和gtk4-rs的例子,还有一个gtk-rs贡献者的online book。