10.6. Aspect Frames

The aspect frame widget is like a frame widget, except that it also enforces the aspect ratio (that is, the ratio of the width to the height) of the child widget to have a certain value, adding extra space if necessary. This is useful, for instance, if you want to preview a larger image. The size of the preview should vary when the user resizes the window, but the aspect ratio needs to always match the original image.

To create a new aspect frame use:
 
aspect_frame = GtkAspectFrame(label, xalign, yalign, ratio, obey_child)

label specifies the text to be displayed as the label. xalign and yalign specify alignment as with Alignment widgets. If obey_child is true, the aspect ratio of a child widget will match the aspect ratio of the ideal size it requests. Otherwise, it is given by ratio.

To change the options of an existing aspect frame, you can use:
 
aspect_frame.set(xalign, yalign, ratio, obey_child)

As an example, the aspectframe.py program uses an AspectFrame to present a drawing area whose aspect ratio will always be 2:1, no matter how the user resizes the top-level window. Figure 10.5 illustrates the display of the program:

Figure 10.5 Aspect Frame Example

The source code for aspectframe.py is:
 
    1   #!/usr/bin/env python
    2   
    3   # example aspectframe.py
    4   
    5   import gtk
    6   
    7   class AspectFrameExample:
    8       def __init__(self):
    9           window = gtk.GtkWindow(gtk.WINDOW_TOPLEVEL);
   10           window.set_title("Aspect Frame")
   11           window.connect("destroy", gtk.mainquit)
   12           window.set_border_width(10)
   13   
   14           # Create an aspect_frame and add it to our toplevel window
   15           aspect_frame = gtk.GtkAspectFrame("2x1", # label
   16                                             0.5, # center x
   17                                             0.5, # center y
   18                                             2, # xsize/ysize = 2
   19                                             gtk.FALSE) # ignore child's aspect
   20           window.add(aspect_frame)
   21           aspect_frame.show()
   22   
   23           # Now add a child widget to the aspect frame
   24           drawing_area = gtk.GtkDrawingArea()
   25   
   26           # Ask for a 200x200 window, but the AspectFrame will give us a 200x100
   27           # window since we are forcing a 2x1 aspect ratio
   28           drawing_area.set_usize(200, 200)
   29           aspect_frame.add(drawing_area)
   30           drawing_area.show()
   31           window.show()
   32   
   33   def main():
   34       gtk.mainloop()
   35       return 0
   36   
   37   if __name__ == "__main__":
   38       AspectFrameExample()
   39       main()