4.2. An Upgraded Hello World

Let's take a look at a slightly improved helloworld.rb with better examples of callbacks. This will also introduce us to our next topic, packing widgets.

require 'gtk2'

def callback( widget )
   puts "Hello again - #{widget} was pressed."
end

def delete_event( widget, event )
   Gtk.main_quit
   return false
end

# This is called in all Ruby-GNOME2 applications
Gtk.init

# Create a window
window = Gtk::Window.new( Gtk::Window::TOPLEVEL )

# New way to set the title of the window
window.title=( "Hello Buttons" )

# Sets a handler for delete_event that immediately
# exits Ruby-GNOME2
window.signal_connect( 'delete_event' ) { |w,e| delete_event( w, e ) }

# New way to set the border width of the window
window.border_width=( 10 )

# We create a box to pack widgets into. This is described in
# detail in the "packing" section. The box is not really 
# visible, it is just used as a tool to arrange widgets.
box1 = Gtk::HBox.new( false, 0 )

# Put the box in the main window
window.add( box1 )

# Creates a new button with the label "Button 1"
button = Gtk::Button.new( "Button 1" )

# Now when the button is clicked, we call the "callback"
# method, passing the widget as an argument.
button.signal_connect( "clicked" ) { |w| callback( w ) }

# Instead of adding the button to the window, we pack this
# button into the invisible box, which has already been
# packed into the window.
box1.pack_start( button, true, true, 0 )

# Always remember this step, this tells GTK that our
# preparation for this button is complete, and it can
# now be displayed.
button.show

# Do these same steps again to create a second button
button2 = Gtk::Button.new( "Button 2" )

# Call the same callback method, with a different argument,
# passing the button2 widget instead.
button2.signal_connect( "clicked" ) { |w| callback(w) }

box1.pack_start( button2, true, true, 0 )

# The order in which we show the buttons is not really
# important, but I recommend showing the window last,
# it all pops up at once.
button2.show

box1.show

window.show

# Rest in Gtk.main and wait for the fireworks to start
Gtk.main

You can run this program using the same methods described in our first example. You'll notice this time there is no easy way to exit the program. You will have to use your window manager or command line to kill it. A good exercise for the reader would be to insert a third "Quit" button that will exit the program. You may also wish to play with the options to Gtk::Box#pack_start while reading the next section. Try resizing the window, and observe the behavior.


Prev Next