如何使用PyGI在Python3中自动调整图像大小?

Bob*_*ble 5 gtk resize image introspection python-3.x

虽然我已经找到了这个问题的部分和间接答案(参见,例如,这个链接),但我在这里发布这个,因为把拼图的部分拼凑起来花了我一点时间,我想其他人可能会找到我的努力使用.

那么,当父窗口调整大小时,如何在GTK +中的按钮上实现图像的无缝调整?

Bob*_*ble 5

在问题中发布的链接中为PyGTK提供的解决方案在使用GTK3的Python-GI中不起作用,尽管使用ScrolledWindow代替常用Box的技巧非常有用.

这是我在按钮上获取图像以使用容器调整大小的最小工作解决方案.

from gi.repository import Gtk, Gdk, GdkPixbuf

class ButtonWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Button Demo")
        self.set_border_width(10)
        self.connect("delete-event", Gtk.main_quit)
        self.connect("check_resize", self.on_check_resize)

        self.box = Gtk.ScrolledWindow()
        self.box.set_policy(Gtk.PolicyType.ALWAYS,
                       Gtk.PolicyType.ALWAYS)
        self.add(self.box)

        self.click = Gtk.Button()
        self.box.add_with_viewport(self.click)

        self.pixbuf = GdkPixbuf.Pixbuf().new_from_file('gtk-logo-rgb.jpg')
        self.image = Gtk.Image().new_from_pixbuf(self.pixbuf)
        self.click.add(self.image)

    def resizeImage(self, x, y):
        print('Resizing Image to ('+str(x)+','+str(y)+')....')
        pixbuf = self.pixbuf.scale_simple(x, y,
                                          GdkPixbuf.InterpType.BILINEAR)
        self.image.set_from_pixbuf(pixbuf)

    def on_check_resize(self, window):
        print("Checking resize....")

        boxAllocation = self.box.get_allocation()
        self.click.set_allocation(boxAllocation)
        self.resizeImage(boxAllocation.width-10,
                         boxAllocation.height-10)

win = ButtonWindow()
win.show_all()
Gtk.main()
Run Code Online (Sandbox Code Playgroud)

(宽度和高度上的-10是为了容纳内部边框和按钮中的填充.我试着摆弄它以在按钮上获得更大的图像,但结果看起来不那么好.)

可以从此处下载此示例中使用的jpeg文件.

我欢迎进一步提出如何做到这一点的建议.