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.


2 thoughts on “Creating Windows With Ruby Tk – Widgets”

Comments are closed.