2. An Upgraded Hello World

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



use Glib qw/TRUE FALSE/;
use Gtk2 '-init';

# Our new improved callback.  The data passed to this function
# is printed to stdout.
sub callback
{
	my ($button, $data) = @_;
	
	print "Hello again - $data was pressed\n";
}

# another callback
sub delete_event
{
	Gtk2->main_quit;
	return FALSE;
}

# Create a new window
$window = Gtk2::Window->new('toplevel');

# This is a new call, which just set the title for our
# new window to "Hello Buttons!"
$window->set_title("Hello Buttons!");

# Here we just set a handler for the delete_event that immediately
# exits GTK.
$window->signal_connect(delete_event => \&delete_event);

# Sets the border width of the window.
$window->set_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 = Gtk2::HBox->new(FALSE, 0);

# Put the box into the main window.
$window->add($box1);

# Creates a new button with the label "Button 1".
$button = Gtk2::Button->new("Button 1");

# Now when the button is clicked, we call the "callback" function
# with the string "button 1" as its argument.
$button->signal_connect(clicked => \&callback, 'button 1');

# Instead of Gtk2::Container::add, we pack this button into the invisible
# box, which has 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 the same steps again to create a second button.
$button = Gtk2::Button->new("Button 2");

# Call the same callback function with a different argument, passing the string
# "button 2" instead.
$button->signal_connect(clicked => \&callback, 'button 2');

$box1->pack_start($button, TRUE, TRUE, 0);

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

$button->show;

$box1->show;

$window->show;

# Rest in main and wait for the fun to begin!
Gtk2->main;

0;


You'll notice this time there is no easy way to exit the program, you 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 Gtk2::Box::pack_start() while reading the next section. Try resizing the window, and observe the behavior.