How to Write GTK Applications with PHP

It is possible to write GTK2 application using PHP. It is a little work to get it compiled and installed, but once configured it is easy to write programs with GTK2. As of June 22, 2015 a development branch has been created for GTK3. Follow these installation instructions first. Then try out the code samples below. Load the php-gtk2 module in your php.ini as well. This is not a complete lesson in how to use GTK and Glade, but a reference on how to use them in the PHP ecosystem. Refer to the PHP-GTK documentation for details on classes and enumerations.

// Create top level window object and give it a title
$window = new GtkWindow();
$window->set_title('Hello world');

// Connect the 'destroy' action to GTK's main_quit function
// so the program exits when the window is closed
$window->connect_simple('destroy', array('gtk', 'main_quit'));

// Add an element to the window
$label = new GtkLabel("Hello\n\nWorld!");

// Tell all windows to set visible

// Run!

// Creating a text field
$textField = new GtkEntry();

// Creating buttons
$button = new GtkButton('Go');

// Labels
$label = new GtkLabel('Text Label', true);
// The mnemonic widget is the element that is triggered
// when the label is clicked. For example a button or text field

// Placing buttons inside a horizontal buttom box
$horizontalButtonBox = new GtkHButtonBox();

// Connecting clicks to buttons
$button->connect_simple('clicked', $callbackFunctionName, $window, $extraParam, $extraParam2);

// Creating a table
//$table->attach($child, $left_attach, $right_attach, $top_attach, $bottom_attach, $xoptions, $yoptions, $xpadding, $ypadding)
// Attach options include expand, shrink, and fill
$table = new GtkTable(3, 2);
$table->attach($label1, 0, 2, 0, 1);
$table->attach($label2, 0, 1, 1, 2);
$table->attach($textField2, 1, 2, 1, 2);
$table->attach($label3, 0, 1, 2, 3);
$table->attach($textField3, 1, 2, 2, 3);

// Getting text from a field
$text = $textField->get_text();
// Dialogs
$dialog = new GtkMessageDialog(
$dialog->set_markup("The following errors occured:\r\n<span foreground='red'>" . $errors . "</span>");

// Loading a Glade file
$glade = new GladeXML('');

// Get element object from Glade (window, buttons, textfields, etc)
$element = $glade->get_widget('myGladeWidget');

For more tutorials, check out the PHP-GTK website.