How to make automatic image resizing in Python3 using PyGI?

Although I found partial and indirect answers to this question (see, for example, this link ), I post it here because it took me a little time to assemble the puzzle pieces and I thought that someone else might find my efforts to use.

So, how to achieve seamless resizing of images on buttons in GTK + when resizing the parent window?

+5
source share
2 answers

The solution proposed for PyGTK in the link posted in the question does not work in Python-GI with GTK3, although the trick of using ScrolledWindow instead of the usual Box was very useful.

.

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

(-10 . , , .)

jpeg, , .

, .

+5

self.image = Gtk.Image().new_from_pixbuf(self.pixbuf) , : self.image = Gtk.Image().set_from_pixbuf(self.pixbuf)

.

0

All Articles