Copyright © tutorialspoint.com

Ruby/Tk - Button Widget

previous next


Description:

A button is very much designed for the user to interact with, and in particular, press to perform some action. A button is a widget that displays a textual string, bitmap or image. If text is displayed, it must all be in a single font, but it can occupy multiple lines on the screen.

A button can display itself in either of three different ways, according to the state option. It can be made to appear raised, sunken, or flat and it can be made to flash.

Syntax:

Here is a simple syntax to create this widget:

TkButton.new(root) {
  .....Standard Options....
  .....Widget-specific Options....
}

Standard Options:

These options have been described in previous chapter.

Widget-specific Options:

SNOptions with Description
1command => String
Specifies a Ruby command to associate with the button. This command is typically invoked when mouse button 1 is released over the button window. Here you can associate a Ruby method to be executed against mouse click. I have done it in the example given below.
2compound => String
Specifies whether the button should display both an image and text, and if so, where the image should be placed relative to the text. Valid values for this option are bottom, center, left, none, right and top. The default value is none, meaning that the button will display either an image or text, depending on the values of the image and bitmap options.
3height => Integer
Specifies a desired height for the button.
4state => String
Specifies one of three states for the button: normal, active, or disabled. In normal state the button is displayed using the foreground and background options. The active state is typically used when the pointer is over the button. In active state the button is displayed using the activeforeground and activebackground options. Disabled state means that the button should be insensitive:
5width => Integer
Specifies a desired width for the button.

Event Bindings:

Ruby/Tk automatically creates class bindings for buttons that give them the following default behavior:

If the button's state is disabled then none of the above actions occur: the button is completely non-responsive.

Examples:

require 'tk'

def myproc
  puts "The user says OK."
  exit
end

root = TkRoot.new
btn_OK = TkButton.new(root) do
  text "OK"
  borderwidth 5
  underline 0
  state "normal"
  cursor "watch"
  font TkFont.new('times 20 bold')
  foreground  "red"
  activebackground "blue"
  relief      "groove"
  command (proc {myproc})
  pack("side" => "right",  "padx"=> "50", "pady"=> "10")
end
Tk.mainloop

This will produce following result if you will click over this button then ruby method myproc would be executed.

Ruby/Tk Button

previous next

Copyright © tutorialspoint.com