Python GTK调整大图像的大小以适合窗口

Python GTK调整大图像的大小以适合窗口

问题描述:

重要提示:我正在使用 PyGObject 来访问GTK小部件,而不是 PyGTK .这就是使这个问题不同于类似问题的原因:

Important note: I'm using PyGObject to get access to the GTK widgets, not PyGTK. That's what makes this question different from similar ones:

我想做一个非常简单的应用程序,该应用程序显示标签,图像和按钮,它们全部堆叠在一起.该应用程序应在全屏模式下运行.

I want to make a very simple app that displays a label, an image and a button, all stacked on top of each other. The app should be running in fullscreen mode.

尝试时,我遇到了问题.我的图像具有很高的分辨率,因此当我仅通过文件创建并添加它时,我几乎看不到它的20%.

When I attempted it, I've run into a problem. My image is of very high resolution, so when I simply create it from file and add it, I can barely see 20% of it.

我想要的是根据窗口的大小(根据应用全屏运行时的屏幕大小)按宽度缩放此图像.

What I want is for this image to be scaled by width according to the size of the window (which is equal to the screen size as the app runs in fullscreen).

我尝试使用Pixbufs,但是在它们上调用 scale_simple 似乎并没有太大改变.

I've tried using Pixbufs, but calling scale_simple on them didn't seem to change much.

这是我当前的代码:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GdkPixbuf


class Window(Gtk.Window):
    def __init__(self):
        super().__init__(title='My app')

        layout = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        dimensions = layout.get_allocation()

        pixbuf = GdkPixbuf.Pixbuf.new_from_file('path/to/image')
        pixbuf.scale_simple(dimensions.width, dimensions.height, GdkPixbuf.InterpType.BILINEAR)
        image = Gtk.Image.new_from_pixbuf(pixbuf)
        dismiss_btn = Gtk.Button(label='Button')

        dismiss_btn.connect('clicked', Gtk.main_quit)
        layout.add(image)
        layout.add(dismiss_btn)
        self.add(layout)


win = Window()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()

问题是,根据 scale_simple 实际上返回了一个新的Pixbuf.org/gdk-pixbuf/stable/gdk-pixbuf-Scaling.html#gdk-pixbuf-scale-simple"rel =" nofollow noreferrer> GTK +文档.

The problem is that scale_simple actually returns a new Pixbuf, as per GTK+ docs.

通过在窗口上调用 .get_screen(),然后调用 .width() .height(),可以获取屏幕尺寸>在屏幕对象上.

Getting screen dimensions can be done by calling .get_screen() on the window and then calling .width() or .height() on the screen object.

放在一起的整个代码看起来像这样:

The whole code put together looks something like this:

screen = self.get_screen()
pixbuf = GdkPixbuf.Pixbuf.new_from_file('/path/to/image')
pixbuf = pixbuf.scale_simple(screen.width(), screen.height() * 0.9, GdkPixbuf.InterpType.BILINEAR)
image = Gtk.Image.new_from_pixbuf(pixbuf)