Python GTK resizing large image to fit inside a window

 ̄綄美尐妖づ 提交于 2021-01-28 03:17:34

问题


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:

  • PyGTK: How do I make an image automatically scale to fit it's parent widget?
  • Scale an image in GTK

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

回答1:


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)


来源:https://stackoverflow.com/questions/50857102/python-gtk-resizing-large-image-to-fit-inside-a-window

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!