1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Tk Widgets


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"

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

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

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

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

See More About
  1. About.com
  2. Technology
  3. Ruby
  4. Graphical User Interfaces
  5. Tk
  6. Getting it All Together

©2014 About.com. All rights reserved.