Ruby TK – Arranging Widgets With Grids

What would you do if you wanted your widgets arranged in a tabular structures? For example: a list of labels followed by input fields.

Well, you would divide your window and other widgets into grid, and would justify the contents of grids right, left, up, down, etc.

You can choose the location of your widget in its parent widget, by adding the ‘grid’ method in the block following the ‘new’ method.

For example:

  TkLabel.new(root) do
    background 'white'
    text 'username:'
    grid('row'=>8, 'column'=>0, 'sticky'=>'e', 'padx'=>5)
  end

Explanation:
'sticky'=>'e' means justifying right. e=east, w=west, ne=northeast, etc.
'padx' is the number of pixels following the elements. In the picture, you can see 5
      pixels between the text 'username' and the input field.

When you add a grid to a widget, don't use 'pack'!! This will confuse Tk,
and will result in a program that does not respond!
Advertisement