Вот небольшой фрагмент кода, который позволяет использовать автоматически масштабированное изображение.
import gtk
class ImageEx(gtk.Image):
pixbuf = None
def __init__(self, *args, **kwargs):
super(ImageEx, self).__init__(*args, **kwargs)
self.connect("size-allocate", self.on_size_allocate)
def set_pixbuf(self, pixbuf):
"""
use this function instead set_from_pixbuf
it sets additional pixbuf, which allows to implement autoscaling
"""
self.pixbuf = pixbuf
self.set_from_pixbuf(pixbuf)
def on_size_allocate(self, obj, rect):
# skip if no pixbuf set
if self.pixbuf is None:
return
# calculate proportions for image widget and for image
k_pixbuf = float(self.pixbuf.props.height) / self.pixbuf.props.width
k_rect = float(rect.height) / rect.width
# recalculate new height and width
if k_pixbuf < k_rect:
newWidth = rect.width
newHeight = int(newWidth * k_pixbuf)
else:
newHeight = rect.height
newWidth = int(newHeight / k_pixbuf)
# get internal image pixbuf and check that it not yet have new sizes
# that's allow us to avoid endless size_allocate cycle
base_pixbuf = self.get_pixbuf()
if base_pixbuf.props.height == newHeight and base_pixbuf.props.width == newWidth:
return
# scale image
base_pixbuf = self.pixbuf.scale_simple(
newWidth,
newHeight,
gtk.gdk.INTERP_BILINEAR
)
# set internal image pixbuf to scaled image
self.set_from_pixbuf(base_pixbuf)
И небольшой пример использования:
class MainWindow(object):
def __init__(self):
self.window = gtk.Window()
self.window.connect("destroy", gtk.main_quit)
# create new ImageEx
self.image = ImageEx()
# set size request, to limit image size
self.image.set_size_request(width=400, height=400)
# load image from file, change path with path of some of your image
pixbuf = gtk.gdk.pixbuf_new_from_file("path/to/your/image.jpeg")
# that's the key moment, instead `set_from_pixbuf` function
# we use our newly created set_pixbuf, which do some additional assignments
self.image.set_pixbuf(pixbuf)
# add widget and show window
self.window.add(self.image)
self.window.show_all()
if __name__ == '__main__':
MainWindow()
gtk.main()