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

Tk Widgets

By

3 of 6

Adding a Button
Tk window with a single button widget

A window without anything in it isn't particularly exciting, so adding buttons is the next logical step. The TkButton widget will create a new button with a text label. The following example is the beginning of the "adding" program. This program will have two text input widgets: a button and a label for the result. When the button is pressed, the numbers in the two input widgets will be added together and the result (sum) will be displayed in the label.

Create a root window as described in Step 1. After that, a TkButton widget can be created. You'll notice that the TkButton new method takes an argument. All widgets are the child of another widget. The button's parent widget is the root window, so the root variable is passed as an argument. The block is more or less the same as the block passed to the root widget when it was created. Instead of title, the text to be displayed on the button is defined with text. You'll also notice the pack method called at the end of the block. All widgets must be "packed" inside their parent widgets before they can be displayed--this will be discussed in detail when more widgets have been added to the root window.

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

root = TkRoot.new do
title "Adder"
end

button = TkButton.new(root) do
text "Add"
pack
end

Tk.mainloop
See More About
  1. About.com
  2. Technology
  3. Ruby
  4. Graphical User Interfaces
  5. Tk
  6. Adding a Button

©2014 About.com. All rights reserved.