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: do
    background 'white'
    text 'username:'
    grid('row'=>8, 'column'=>0, 'sticky'=>'e', 'padx'=>5)

'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!

Creating Windows With Ruby Tk – Widgets

In the previous chapter, you saw how to create a simple window. This window is an object of class TkRoot, which is implicitly created when running a Tk application. You better create it explicitly, so you don’t have a default window with a default title. e.g. {title 'My Title'}

TkRoot is a singleton object, and its method ‘new’ does not instantiate an object, but returns an existing one. The method ‘new’ only reads the attached block and performs it to configure the default window. If you want similar windows, use ‘TkToplevel’.

Now, you can add widgets to your windows using

myWidget=<widgetname>.new(<parent>) {<block>}

When ‘widgetname’ is the widget’s class, the class name is ‘Tk’ followed by the widget name as defined in Active Perl.

‘parent’ is the parent widget in which you want to put your new widget. If parent is not specified, your widget will be added to the ‘TkRoot’ window.

‘block’ is a block of commands to be performed, mainly methods to configure your widget. For example {width 90; height 36; background 'blue'}

Because widgets are used for input and output we don’t just put it in windows. For example, a button should response to clicks, so we make it respond to the left click by:

button.bind '1', proc {puts 'button clicked!'}

Or, a common input text field is the widget TkEntry. To read the entered text, we use the expression:

Something I don’t like is that to get the value from a TkCheckbutton widget, you use its get_value method` they can use some consistency.

To set a default value: {insert 0,'some text'}

We can use TkEntry as a password field by invoking the method ‘show’: {show '*'}

To learn more about widgets read ActivePerl.