Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyGTK: How do I make an image automatically scale to fit its parent widget?

I have a PyGTK app that needs to load an image of unknown size, however I am having the problem that if the image is either very big or very small, the window layout becomes distorted and hard to use. I need some way of making the image automatically scale to fit its parent widget. Unfortunately, after doing some research, it seems there is no code, built in or otherwise, that does what I'm looking for.

How could I go about writing something to do this? I would have thought that somebody would have written some code for this already; is there something that I missed?

like image 583
Zaz Avatar asked Feb 21 '11 14:02

Zaz


1 Answers

You can use widget.get_allocation() to find out the size of the parent widget and pixbuf.scale_simple to scale the image, like this:

allocation = parent_widget.get_allocation()
desired_width = allocation.width
desired_height = allocation.height

pixbuf = gtk.gdk.pixbuf_new_from_file('your_image.png')
pixbuf = pixbuf.scale_simple(desired_width, desired_height, gtk.gdk.INTERP_BILINEAR)
image = gtk.image_new_from_pixbuf(pixbuf)

If you want the image to scale each time the window is resized, you'll have to put the code above (or something similar, to avoid loading the image from disk every time) in a function connected to the size_allocate signal of the parent widget. To avoid infinite loops, make sure that the image you put in the widget doesn't alter its size again.

References:

  • How to resize an image (I think you already visited that)
  • About the "resize" event
  • Other link about resizing, in Stack Overflow
like image 67
Jong Bor Lee Avatar answered Oct 04 '22 22:10

Jong Bor Lee