1. Home
  2. Computing & Technology
  3. Ruby

Tk Widgets

By Amanda & Michael Morin, About.com

5 of 6

Getting it All Together

Tk window with all widgets and correct layout

By this point, you know how to create almost any widget, as they're all created in more or less the same way. However, if you just go packing widgets into the root window as we've been doing, you just get a vertical list of all the widgets in the application, which isn't very visually appealing. To create a coherent application, a little more work is involved.

The adder application will have four widgets. To look right, the two entry widgets should go side by side on the top, followed by the button widget with the label widget for the result located at the bottom of the window.

To get widgets to pack side by side, you first have to pack them in a TkFrame object. The TkFrame object is just a container which is, itself, packed on the top of the window. It's created in the same way as other widgets, but alters how some other widgets are created. Widgets that you want inside the frame need to be created with the frame as their parent. Pass the left side as an argument to the pack method to pack the widgets side-by-side.

Finally, the button and label are also packed on the top side, just as the frame was. Remember that widgets are packed in the order in which their pack methods are called, so the packing algorithm will pack the frame (which contains the two text entry widgets), the button and the label in order from top to bottom.

#!/usr/bin/env ruby
require 'tk'

root = TkRoot.new do
title "Adder"
end

# Text fields
entry_frame = TkFrame.new(root) do
pack 'side' => 'top'
end

entry1 = TkEntry.new(entry_frame) do
pack 'side' => 'left'
end
entry2 = TkEntry.new(entry_frame) do
pack 'side' => 'right'
end

# Button and result label
button = TkButton.new(root) do
text "Add"
pack 'side' => 'top'
end

label = TkLabel.new(root) do
text "The result is: "
pack 'side' => 'top'
end

Tk.mainloop
Explore Ruby
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Ruby
  4. GUI
  5. Tk
  6. Getting it All Together

©2009 About.com, a part of The New York Times Company.

All rights reserved.