首页 > 解决方案 > Python GTK resizing large image to fit inside a window

问题描述

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.

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).

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

Here's my current code:

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()

标签: pythongtkpygobjectimage-scaling

解决方案


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

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)

推荐阅读