Python – Grid container in GTK+ 3
Gtk.Grid
is a container which arranges its child widgets in rows and columns, without the specification of the dimensions in the constructor. Children are added using Gtk.Grid.attac
h(). They can span multiple rows or columns.
The
Gtk.Grid.attach()
method takes five parameters:
child
: theGtk.Widget
to add.
left
: the column number to attach the left side ofchild
to.
top
: indicates the row number to attach the top side ofchild
to.
width
: indicates the number of columns that thechild
will span.
height
: indicates the number of rows that thechild
will span.
Adding a child next to existing child is also possible using Gtk.Grid.attach_next_to()
.
The
Gtk.Grid.attach_next_to
method takes five parameters:
child
:Gtk.Widget to add.
sibling
: an existingchild
widget of aGtk.Grid
or None. The child widget will be placed next tosibling
.
side
:Gtk.PositionType
indicating the side of sibling.
width
: indicate the number of columns thechild
widget will span.
height
: indicate the number of rows thechild
widget will span
Follow below steps:
- import GTK+ 3 module.
- Create main window.
- Create button.
- Create grid.
Note: In IDE’s like Pycharm we can install a package named PyGObject in order to use GTK+ 3.
import gi # Since a system can have multiple versions # of GTK + installed, we want to make # sure that we are importing GTK + 3. gi.require_version( "Gtk" , "3.0" ) from gi.repository import Gtk class GridWin(Gtk.Window): def __init__( self ): Gtk.Window.__init__( self , title = "GfG" ) grid = Gtk.Grid() self .add(grid) button1 = Gtk.Button(label = "Button 1" ) button2 = Gtk.Button(label = "Button 2" ) button3 = Gtk.Button(label = "Button 3" ) button4 = Gtk.Button(label = "Button 4" ) button5 = Gtk.Button(label = "Button 5" ) button6 = Gtk.Button(label = "Button 6" ) grid.add(button1) # With in parentheses child, left, top, width, # height respectively grid.attach(button2, 1 , 0 , 2 , 1 ) # With in parentheses child, sibling, left, top, width, # height respectively grid.attach_next_to(button3, button1, Gtk.PositionType.BOTTOM, 1 , 2 ) grid.attach_next_to(button4, button3, Gtk.PositionType.RIGHT, 1 , 1 ) grid.attach(button5, 1 , 2 , 1 , 1 ) grid.attach_next_to(button6, button4, Gtk.PositionType.RIGHT, 1 , 2 ) win = GridWin() win.connect( "destroy" , Gtk.main_quit) win.show_all() Gtk.main() |
Output :