Calculator in PHP GTK2

|
Free Simple Calculator in php gtk2 with source code. This calculator perform basic arithmetic operations i.e Addition, Subtraction, Multiplication, Division. Hope you like it. Thanks! For reading my Blog.

<?php
/* 
PHP GTK tutorials
website: http://phpgtktutorials.blogspot.in/
*/

if (!class_exists('gtk')) {
    die("Please load the php-gtk2 module in your php.ini\r\n");
}


$wnd = new GtkWindow();
$action = NULL;
$firstValue = NULL;
$result =NULL;

function pressClear(GtkWindow $wnd, GtkEntry $txtEntry, $txtButton)
{
    //clear $txtEntry
    $txtEntry->set_text($txtButton);
    
}

function pressBack(GtkWindow $wnd, GtkEntry $txtEntry)
{
    //backspace
    $txtEntryValue = $txtEntry->get_text();
    $newTxtEntryValue = substr("$txtEntryValue", 0, -1);
    $txtEntry->set_text($newTxtEntryValue);
}


function pressAction(GtkWindow $wnd, GtkEntry $txtEntry, $currentAction, $label, $action)
{

$firstValue = $txtEntry->get_text();
$txtEntry->set_text(NULL);

$label->set_text($firstValue);
$action->set_text($currentAction);


}


function pressEqualto(GtkWindow $wnd, GtkEntry $txtEntry, $action, $label)
{
    $secondValue = $txtEntry->get_text();
    $firstValue = $label->get_text();
    $currentaction = $action->get_text();

    if($currentaction=="+")
    {
        $result = $firstValue+$secondValue;
    }
    elseif ($currentaction=="*") {
        
        $result = $firstValue*$secondValue;
    }
    elseif ($currentaction=="/") {
        
        $result = $firstValue/$secondValue;
    }
    elseif ($currentaction=="-") {
        
        $result = $firstValue-$secondValue;
    }

    $txtEntry->set_text($result);


}



function pressButton(GtkWindow $wnd, GtkEntry $txtEntry, $txtButton)
{
    //get the values from the widgets into variables
    $txtEntryValue = $txtEntry->get_text();
    

    if(empty($txtEntryValue))
    {

        $txtEntry->set_text($txtButton);
        
    }else{

        $txtEntry->set_text($txtEntryValue.$txtButton);

    }    



}



        $wnd->set_title('Calculator');         
        $wnd->connect_simple('destroy', array('gtk', 'main_quit')); 

        $vbox = new GtkVBox(false, 2);

        $mb = new GtkMenubar();
        $filemenu = new GtkMenu();
        $filemi = new GtkMenuItem("File");
        $filemi->set_submenu($filemenu);
        $mb->append($filemi);

        $vbox->pack_start($mb, false, false, 0);

        $table = new GtkTable(5, 4, true);

        // Set up all the widgets we need
        $btnClose = new GtkButton("_Close");

        $btnOne = new GtkButton("1");
        $btnTwo = new GtkButton("2");
        $btnThree = new GtkButton("3");
        $btnFour = new GtkButton("4");
        $btnFive = new GtkButton("5");
        $btnSix = new GtkButton("6");
        $btnSeven = new GtkButton("7");
        $btnEight = new GtkButton("8");
        $btnNine = new GtkButton("9");
        $btnZero = new GtkButton("0");

        $btnClear = new GtkButton("Clear");
        $btnBack = new GtkButton("Clear Entry");

        $btnAddition = new GtkButton("+");
        $btnDivide = new GtkButton("/");
        $btnMinus = new GtkButton("-");
        $btnProduct = new GtkButton("*");
        $btnEqualto = new GtkButton("=");

        $labelHidden = new GtkLabel(); // store firstvalue
        $labelAction = new GtkLabel(); // store operations

        $table->attach($btnClear, 0, 1, 0, 1);
        $table->attach($btnBack, 1, 2, 0, 1);
        @$wnd->set_title($labelHidden);
        @$wnd->set_title($labelAction);

        $table->attach($btnClose, 3, 4, 0, 1);

        $table->attach($btnSeven, 0, 1, 1, 2);
        $table->attach($btnEight, 1, 2, 1, 2);
        $table->attach($btnNine, 2, 3, 1, 2);
        $table->attach($btnDivide, 3, 4, 1, 2);

        $table->attach($btnFour, 0, 1, 2, 3);
        $table->attach($btnFive, 1, 2, 2, 3);
        $table->attach($btnSix, 2, 3, 2, 3);
        $table->attach($btnProduct, 3, 4, 2, 3);

        $table->attach($btnOne, 0, 1, 3, 4);
        $table->attach($btnTwo, 1, 2, 3, 4);
        $table->attach($btnThree, 2, 3, 3, 4);
        $table->attach($btnMinus, 3, 4, 3, 4);

        $table->attach($btnZero, 0, 1, 4, 5);
        $table->attach(new GtkButton("."), 1, 2, 4, 5);
        $table->attach($btnEqualto, 2, 3, 4, 5);
        $table->attach($btnAddition, 3, 4, 4, 5);

        $txtEntry = new GtkEntry();
        $vbox->pack_start($txtEntry, false, false, 0);
        $vbox->pack_end($table, true, true, 0);

        $wnd->add($vbox);        


        // Destroy the window when the user clicks Close button
        $btnClose->connect_simple('clicked', array($wnd, 'destroy'));

        // Clear entry label  when the user clicks Clear button
        $btnClear->connect_simple('clicked', 'pressClear', $wnd, $txtEntry, NULL);

        // BackSpace label  when the user clicks Back button
        $btnBack->connect_simple('clicked', 'pressBack', $wnd, $txtEntry);

        // Call the pressEqualto function 
        $btnEqualto->connect_simple('clicked', 'pressEqualto', $wnd, $txtEntry, $labelAction, $labelHidden);

        // Call the pressAction function when the user clicks on numeric button
        $btnAddition->connect_simple('clicked', 'pressAction', $wnd, $txtEntry, "+", $labelHidden, $labelAction);
        $btnDivide->connect_simple('clicked', 'pressAction', $wnd, $txtEntry, "/", $labelHidden, $labelAction);
        $btnMinus->connect_simple('clicked', 'pressAction', $wnd, $txtEntry, "-", $labelHidden, $labelAction);
        $btnProduct->connect_simple('clicked', 'pressAction', $wnd, $txtEntry, "*", $labelHidden, $labelAction);
 
        // Call the pressButton function when the user clicks on numeric button
        $btnOne->connect_simple('clicked', 'pressButton', $wnd, $txtEntry, "1");
        $btnTwo->connect_simple('clicked', 'pressButton', $wnd, $txtEntry, "2");
        $btnThree->connect_simple('clicked', 'pressButton', $wnd, $txtEntry, "3");
        $btnFour->connect_simple('clicked', 'pressButton', $wnd, $txtEntry, "4");
        $btnFive->connect_simple('clicked', 'pressButton', $wnd, $txtEntry, "5");
        $btnSix->connect_simple('clicked', 'pressButton', $wnd, $txtEntry, "6");
        $btnSeven->connect_simple('clicked', 'pressButton', $wnd, $txtEntry, "7");
        $btnEight->connect_simple('clicked', 'pressButton', $wnd, $txtEntry, "8");
        $btnNine->connect_simple('clicked', 'pressButton', $wnd, $txtEntry, "9");
        $btnZero->connect_simple('clicked', 'pressButton', $wnd, $txtEntry, "0");


        $wnd->set_default_size(300, 250); 
        $wnd->set_position(GTK::WIN_POS_CENTER);
                
 

//Show all widgets
$wnd->show_all();
//Start the main loop
Gtk::main();

?>

Signal Handling in PHP GTK (Click Event)

|
In this post we learn how to handle Signals in the PHP-GTK library. Create click listeners for your desktop application. Classes used in this code are include GtkWindow, GtkButton and GtkHButtonBox. Develop your own desktop applications with PHP.

Create window.php file
<?php
/* 
PHP GTK tutorials
website: http://phpgtktutorials.blogspot.in/
*/


$window = new GtkWindow();
$window->set_title("Signal Handling in PHP GTK");
$window->connect_simple("destroy",array("Gtk","main_quit"));

$button1 = new GtkButton("Button 1");
$button2 = new GtkButton("Button 2");

function signalClicked($button)
{
echo $button->get_label()." was clicked.\n";
}

$button1->connect("clicked","signalClicked");
$button2->connect("clicked","signalClicked");

$bb = new GtkHButtonBox();
$bb->set_layout(Gtk::BUTTONBOX_EDGE);
$bb->add($button1);
$bb->add($button2);

$window->add($bb);
$window->show_all();
Gtk::main();

?>

Custom Widget in GTK and PHP

|
Toolkits usually provide only the most common widgets like buttons, text widgets, sliders etc. No toolkit can provide all possible widgets. If there is a need for a more specialized widget, we must create it ourselves.

Custom widgets are created by using the drawing tools provided by the toolkit. There are two possibilities. A programmer can modify or enhance an existing widget. Or he can create a custom widget from scratch.

Burning widget

This is an example of a widget, that we create from scratch. It is based on a minimal GtkWidget widget. This custom widget can be found in various media burning applications, like Nero Burning ROM.
<?php
/* 
 
PHP GTK tutorials
website: http://phpgtktutorials.blogspot.in/
 
*/

class Burning extends GtkDrawingArea { 
     

    public function __construct($par) { 

        parent::__construct(); 
 
        $this->par = $par;          

        $this->init_ui();

    } 

    public function init_ui() {

        $this->num = array("75", "150", "225", "300", 
            "375", "450", "525", "600", "675");
 
        $this->set_size_request(1, 30);
        $this->connect('expose_event', array($this, 'on_expose')); 
 
    }

    public function on_expose() {
        $cr = $this->window->cairo_create();
        $this->draw_widget($cr);
    }

    public function draw_widget($cr) {
 
        $cr->SetLineWidth(0.8);
        $cr->SelectFontFace("Courier", CairoFontSlant::NORMAL, 
            CairoFontWeight::NORMAL);
        $cr->SetFontSize(11);

        $width = $this->get_allocation()->width;
     
        $this->cur_width = $this->par->get_cur_value();

        $step = round($width / 10.0);

        $till = ($width / 750.0) * $this->cur_width;
        $full = ($width / 750.0) * 700;

        if ($this->cur_width >= 700) {
            
            $cr->SetSourceRgb(1.0, 1.0, 0.72);
            $cr->Rectangle(0, 0, $full, 30);
            $cr->Clip();
            $cr->Paint();
            $cr->ResetClip();
            
            $cr->SetSourceRgb(1.0, 0.68, 0.68).
            $cr->Rectangle($full, 0, $till-$full, 30);
            $cr->Clip();
            $cr->Paint();
            $cr->ResetClip();

        } else {
            $cr->SetSourceRgb(1.0, 1.0, 0.72);
            $cr->Rectangle(0, 0, $till, 30);
            $cr->Clip();
            $cr->Paint();
            $cr->ResetClip();
        }
       

        $cr->SetSourceRgb(0.35, 0.31, 0.24);
        $len = count($this->num);

        for ($i=1; $i <= $len; $i++) {
            $cr->MoveTo($i*$step, 0);
            $cr->LineTo($i*$step, 5);
            $cr->Stroke();
            
            $te = $cr->TextExtents($this->num[$i-1]);
            $cr->MoveTo($i*$step-$te['width']/2, 15);
            $cr->TextPath($this->num[$i-1]);
            $cr->Stroke();
        }        
    }
}
            

class Example extends GtkWindow { 
     

    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();

    } 

    private function init_ui() {

        $this->set_title('Burning widget');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 

        $this->cur_value = 0;
       
        $vbox = new GtkVBox(false, 2);
        
        $scale = new GtkHScale();
        $scale->set_range(0, 750);
        $scale->set_digits(0);
        $scale->set_size_request(160, 35);
        $scale->set_value($this->cur_value);
        
        $scale->connect('value-changed', array($this, 'on_changed'));
        
        $fixed = new GtkFixed();
        $fixed->put($scale, 50, 50);
        
        $vbox->pack_start($fixed);
        
        $this->burning = new Burning($this);
        $vbox->pack_start($this->burning, false, false, 0);

        $this->add($vbox);

        $this->set_default_size(350, 200); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();         
    }

    public function on_changed($sender) {
    
        $this->cur_value = $sender->get_value();
        $this->burning->queue_draw();
    }
    
    public function get_cur_value() {
        return $this->cur_value;
    }
} 
     
new Example(); 
Gtk::main();


?>

We put a GtkDrawingArea on the bottom of the window and draw the entire widget manually. All the important code resides in the draw_widget() which is called from the on_expose() method of the Burning class. This widget shows graphically the total capacity of a medium and the free space available to us. The widget is controlled by a scale widget. The minimum value of our custom widget is 0, the maximum is 750. If we reach value 700, we began drawing in red color. This normally indicates overburning.
$this->num = array("75", "150", "225", "300", 
    "375", "450", "525", "600", "675");
These numbers are shown on the burning widget. They show the capacity of the medium.
$this->cur_width = $this->par->get_cur_value();
From the parent widget, we get the current value of the scale widget.
$till = ($width / 750.0) * $this->cur_width;
$full = ($width / 750.0) * 700;
We use the $width variable to do the transformations. Between the values of the scale and the custom widget's measures. Note that we use floating point values. We get greater precision in drawing. The $till parameter determines the total size to be drawn. This value comes from the slider widget. It is a proportion of the whole area. The $full parameter determines the point, where we begin to draw in red color.
$cr->SetSourceRgb(1.0, 1.0, 0.72);
$cr->Rectangle(0, 0, $full, 30);
$cr->Clip();
$cr->Paint();
$cr->ResetClip();
We draw a yellow rectangle up to point, where the medium is full.
$te = $cr->TextExtents($this->num[$i-1]);
$cr->MoveTo($i*$step-$te['width']/2, 15);
$cr->TextPath($this->num[$i-1]);
$cr->Stroke();
This code here draws the numbers on the burning widget. We calculate the text extents to position the text correctly.
public function on_changed($sender) {

    $this->cur_value = $sender->get_value();
    $this->burning->queue_draw();
}
We get the value from the scale widget, store it in the $this->cur_value variable for later use. We redraw the burning widget.

Windows or Dialogs in PHP GTK

|
Dialog windows or dialogs are an indispensable part of most modern GUI applications. A dialog is defined as a conversation between two or more persons. In a computer application a dialog is a window which is used to "talk" to the application. A dialog is used to input data, modify data, change the application settings etc. Dialogs are important means of communication between a user and a computer program.

GtkMessageDialog

Message dialogs are convenient dialogs that provide messages to the user of the application. The message consists of textual and image data. The GtkMessageDialogis used to create message dialogs.
<?php
/* 
 
PHP GTK tutorials
website: http://phpgtktutorials.blogspot.in/
 
*/


class Example extends GtkWindow { 
     
    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();

    } 

    public function init_ui() {

        $this->set_title('GtkMessageDialog');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 

        $fixed = new GtkFixed();              

        $button = new GtkButton("Information");
        $button->set_size_request($button->size_request());
        $button->connect('clicked', array($this, 'on_clicked'));
        
        $fixed->put($button, 50, 50);
        $this->add($fixed); 

        $this->set_default_size(250, 200); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();         
    }

    public function on_clicked($sender) {

            $md = new GtkMessageDialog($this, Gtk::DIALOG_MODAL,
                Gtk::MESSAGE_INFO, Gtk::BUTTONS_OK, "Download completed.");
            $md->set_title("Information");    
            $md->run();
            $md->destroy();
    }
} 
     
new Example(); 
Gtk::main();

?>
We show a button on the window. When we click on the button, an information message is displayed.
$button = new GtkButton("Information");
This is a button, which will show a dialog, when we click on it.
public function on_clicked($sender) {

        $md = new GtkMessageDialog($this, Gtk::DIALOG_MODAL,
            Gtk::MESSAGE_INFO, Gtk::BUTTONS_OK, "Download completed.");
        $md->set_title("Information");    
        $md->run();
        $md->destroy();
}
If we click on the info button, the Information dialog is displayed. TheGtk::DIALOG_MODAL flag makes the dialog modal. The Gtk::MESSAGE_INFO specifies the type of the dialog. In our case it is an information dialog. Different icons are chosen for various dialog types. The Gtk::BUTTONS_OK shows the OK button on the dialog. The last parameter is the message displayed. We set the title of the dialog with the set_title() method. The dialog is displayed with the run() method. The programmer must also call either the destroy() or the hide() method in the end.

GtkAboutDialog

The GtkAboutDialog displays information about the application. It can display a logo, the name of the application, version, copyright, website or license information. It is also possible to give credits to the authors, documenters, translators and artists.
<?php
/* 
 
PHP GTK tutorials
website: http://phpgtktutorials.blogspot.in/
 
*/

class Example extends GtkWindow { 
     
    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();

    } 

    public function init_ui() {

        $this->set_title('About Battery');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 

        $fixed = new GtkFixed();              

        $button = new GtkButton("About");
        $button->set_size_request(80, 30);
        $button->connect('clicked', array($this, 'on_clicked'));
        
        $fixed->put($button, 50, 50);
        $this->add($fixed); 

        $this->set_default_size(250, 200); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();         
    }

    public function on_clicked($sender) {

        $about = new GtkAboutDialog();
        $about->set_program_name("Battery");
        $about->set_version("0.1");
        $about->set_copyright("(c) phpgtktutorials.blogspot.in");
        $about->set_comments("Battery is a simple tool for battery checking");
        $about->set_website("http://phpgtktutorials.blogspot.in/");
        $about->set_logo(GdkPixbuf::new_from_file("battery.png"));
        $about->run();
        $about->destroy();
    }

} 
     
new Example(); 
Gtk::main();


?>
The code example uses a GtkAboutDialog with some of its features.
$about = new GtkAboutDialog();
We create an instance of the GtkAboutDialog.
$about->set_program_name("Battery");
$about->set_version("7.0");
$about->set_copyright("(c) phpgtktutorials.blogspot.in");
Here we specify the name, the version and the copyright of the program.
$about->set_logo(GdkPixbuf::new_from_file("battery.png"));
This line creates a logo.

GtkFontSelectionDialog

The GtkFontSelectionDialog is a dialog for selecting fonts. It is typically used in applications, that do some text editing or formatting.
<?php
/* 
 
PHP GTK tutorials
website: http://phpgtktutorials.blogspot.in/
 
*/
class Example extends GtkWindow { 
     
    private $label;

    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();

    } 

    private function init_ui() {

        $this->set_title('FontSelectionDialog');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 

        $this->set_border_width(10);
        $this->label = new GtkLabel("The only victory over love is flight.");
        $button = new GtkButton("Select font");
        $button->connect('clicked', array($this, 'on_clicked'));

        $fixed = new GtkFixed();
        $fixed->put($button, 100, 30);
        $fixed->put($this->label, 30, 90);
        $this->add($fixed);
       
        $this->set_default_size(350, 200); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();         
    }

    public function on_clicked($sender) {

        $fdia = new GtkFontSelectionDialog("Select font name");
        $response = $fdia->run();
              
        if ($response == Gtk::RESPONSE_OK) {

            $font_desc = new PangoFontDescription($fdia->get_font_name());
            print($fdia->get_font_name());
            if ($font_desc) {
                $this->label->modify_font($font_desc);
            }
            
        }

        $fdia->destroy();
    }
} 
     
new Example(); 
Gtk::main();



?>
In the code example, we have a button and a label. We show theGtkFontSelectionDialog by clicking on the button.
$fdia = new GtkFontSelectionDialog("Select font name");
We create the GtkFontSelectionDialog.
if ($response == Gtk::RESPONSE_OK) {

    $font_desc = new PangoFontDescription($fdia->get_font_name());
    print($fdia->get_font_name());
    if ($font_desc) {
        $this->label->modify_font($font_desc);
    }
    
}
If we click on the OK button, the font of the label widget changes to the one, that we selected in the dialog.

GtkColorSelectionDialog

The GtkFontSelectionDialog is a dialog for selecting colors.
<?php
/* 
 
PHP GTK tutorials
website: http://phpgtktutorials.blogspot.in/
 
*/

class Example extends GtkWindow { 
     
    private $label;

    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();

    } 

    private function init_ui() {

        $this->set_title('GtkColorSelectionDialog');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 

        $this->set_border_width(10);
        $this->label = new GtkLabel("The only victory over love is flight.");
        $button = new GtkButton("Select color");
        $button->connect('clicked', array($this, 'on_clicked'));

        $fixed = new GtkFixed();
        $fixed->put($button, 100, 30);
        $fixed->put($this->label, 30, 90);
        $this->add($fixed);
       
        $this->set_default_size(350, 200); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();         
    }

    public function on_clicked($sender) {

        $cdia = new GtkColorSelectionDialog("Select color");
        $response = $cdia->run();
              
        if ($response == Gtk::RESPONSE_OK) {
            $colorsel = $cdia->colorsel;
            $color = $colorsel->get_current_color();
            $this->label->modify_fg(Gtk::STATE_NORMAL, $color);
        }
        
        $cdia->destroy();
    }
} 
     
new Example(); 
Gtk::main();


?>
The example is very similar to the previous one. This time we change the color of the label.
$cdia = new GtkColorSelectionDialog("Select color");
$response = $cdia->run();
We create and run the GtkFontSelectionDialog.
if ($response == Gtk::RESPONSE_OK) {
    $colorsel = $cdia->colorsel;
    $color = $colorsel->get_current_color();
    $this->label->modify_fg(Gtk::STATE_NORMAL, $color);
}
If the user presses OK, we get the color value and modify the label's color.








Work with menus and toolbars PHP GTK

|
A common part in a GUI application is a menubar. A menubar consists of objects called menus. Top-level menus have their labels on the menubar. The menus have menu items. Menu items are commands that perform a specific action inside the application. Menus can also have submenus, which have their own menu items.


Simple menu

In our first example, we will create a menubar with one file menu. The menu will have only one menu item. By selecting the item the application quits.
<?php
/* 
 
PHP GTK tutorials
website: http://phpgtktutorials.blogspot.in/
 
*/

class Example extends GtkWindow { 
     

    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();

    } 

    public function init_ui() {

        $this->set_title('Simple menu');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 

        $this->modify_bg(Gtk::STATE_NORMAL, new GdkColor(6400, 6400, 6440));
       
        $mb = new GtkMenuBar();

        $filemenu = new GtkMenu();
        $filemi = new GtkMenuItem("File");
        $filemi->set_submenu($filemenu);
       
        $exitmi = new GtkMenuItem("Exit");
        $exitmi->connect_simple('activate', array('gtk', 'main_quit'));              
        $filemenu->append($exitmi);

        $mb->append($filemi);

        $vbox = new GtkVBox(false, 2);
        $vbox->pack_start($mb, false, false, 0);

        $this->add($vbox);

        $this->set_default_size(250, 200); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();         
    }
} 
     
new Example(); 
Gtk::main();

?>

This is a small example with minimal menubar functionality.
$mb = new GtkMenuBar();
The GtkMenuBar widget is created. This is a container for the individual menus.
$filemenu = new GtkMenu();
$filemi = new GtkMenuItem("File");
$filemi->set_submenu($filemenu);
Toplevel GtkMenuItem is created. A menu item represents an action in a GUI application.
$exitmi = new GtkMenuItem("Exit");
$exitmi->connect_simple('activate', array('gtk', 'main_quit'));              
$filemenu->append($exitmi);
Exit GtkMenuItem is created and appended to the File GtkMenuItem.
$mb->append($filemi);
Toplevel GtkMenuItem is appended to the GtkMenuBar widget.
$vbox = new GtkVBox(false, 2);
$vbox->pack_start($mb, false, false, 0);

Submenu

Our final example demonstrates how to create a submenu. A submenu is a menu inside another menu.
<?php
/* 
 
PHP GTK tutorials
website: http://phpgtktutorials.blogspot.in/
 
*/

class Example extends GtkWindow { 
     

    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();

    } 

    public function init_ui() {

        $this->set_title('Submenu');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 

        $this->modify_bg(Gtk::STATE_NORMAL, new GdkColor(6400, 6400, 6440));
       
        $mb = new GtkMenuBar();

        $filemenu = new GtkMenu();
        $filemi = new GtkMenuItem("File");
        $filemi->set_submenu($filemenu);

        $mb->append($filemi);

        $imenu = new GtkMenu();

        $importm = new GtkMenuItem("Import");
        $importm->set_submenu($imenu);

        $inews = new GtkMenuItem("Import news feed...");
        $ibookmarks = new GtkMenuItem("Import bookmarks...");
        $imail = new GtkMenuItem("Import mail...");

        $imenu->append($inews);
        $imenu->append($ibookmarks);
        $imenu->append($imail);

        $filemenu->append($importm);
       
        $exitmi = new GtkMenuItem("Exit");
        $exitmi->connect_simple('activate', array('gtk', 'main_quit'));
                
        $filemenu->append($exitmi);

        $vbox = new GtkVBox(false, 2);
        $vbox->pack_start($mb, false, false, 0);

        $this->add($vbox);

        $this->set_default_size(320, 250); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();         
    }
} 
     
new Example(); 
Gtk::main();

?>
Submenu creation.
$imenu = new GtkMenu();
A submenu is a regular GtkMenu.
$importm = new GtkMenuItem("Import");
$importm->set_submenu($imenu);
It is a submenu of a menu item, which belogs to toplevel file menu.
$inews = new GtkMenuItem("Import news feed...");
$ibookmarks = new GtkMenuItem("Import bookmarks...");
$imail = new GtkMenuItem("Import mail...");

$imenu->append($inews);
$imenu->append($ibookmarks);
$imenu->append($imail);
Submenus have their own menu items.

Image menu

In the next example, we will further explore the menus. We will add images and accelerators to our menu items. Accelerators are keyboard shortcuts for activating menu items.
<?php
/* 
 
PHP GTK tutorials
website: http://phpgtktutorials.blogspot.in/
 
*/

class Example extends GtkWindow { 
     

    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();

    } 

    public function init_ui() {

        $this->set_title('Image menu');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 

        $this->modify_bg(Gtk::STATE_NORMAL, new GdkColor(6400, 6400, 6440));
       
        $mb = new GtkMenuBar();

        $filemenu = new GtkMenu();
        $filemi = new GtkMenuItem("File");
        $filemi->set_submenu($filemenu);

        $mb->append($filemi);


        $agr = new GtkAccelGroup();
        $this->add_accel_group($agr);

        $newi = new GtkImageMenuItem(Gtk::STOCK_NEW, $agr);
        $newi->add_accelerator('activate', $agr, Gdk::KEY_N, 
             Gdk::CONTROL_MASK, Gtk::ACCEL_VISIBLE);
        $newi->connect_simple('activate', array($this, 'on_new_selected')); 
        $filemenu->append($newi);

        $openmi = new GtkImageMenuItem(Gtk::STOCK_OPEN, $agr);
        $openmi->add_accelerator('activate', $agr, Gdk::KEY_O, 
             Gdk::CONTROL_MASK, Gtk::ACCEL_VISIBLE);
        $filemenu->append($openmi);

        $sep = new GtkSeparatorMenuItem();
        $filemenu->append($sep);

        $exitmi = new GtkImageMenuItem(Gtk::STOCK_QUIT, $agr);
        $exitmi->add_accelerator('activate', $agr, Gdk::KEY_Q, 
             Gdk::CONTROL_MASK, Gtk::ACCEL_VISIBLE);
        $exitmi->connect_simple('activate', array('gtk', 'main_quit'));     
        $filemenu->append($exitmi);       
       
        $vbox = new GtkVBox(false, 2);
        $vbox->pack_start($mb, false, false, 0);

        $this->add($vbox);

        $this->set_default_size(320, 250); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();         
    }

    public function on_new_selected() {
        print "new";
    }

} 
     
new Example(); 
Gtk::main();

?>
Our example shows a toplevel menu item with three sublevel menu items. Each of the menu items has an image and an accelerator. The accelerator for the quit menu item quits the application. The accelerator for the new menu item prints 'new' to the console.
$agr = new GtkAccelGroup();
$this->add_accel_group($agr);
To work with accelerators, we create a global GtkAccelGroup object. It will be used later.
$newi = new GtkImageMenuItem(Gtk::STOCK_NEW, $agr);
$newi->add_accelerator('activate', $agr, Gdk::KEY_N, 
      Gdk::CONTROL_MASK, Gtk::ACCEL_VISIBLE);
$newi->connect_simple('activate', array($this, 'on_new_selected')); 
$filemenu->append($newi);
GtkImageMenuItem is created. The image comes from the stock of images. We create also a Ctrl+N accelerator. When we select the menu item with a mouse or press the accelerator, a message is printed to the console.
$sep = new GtkSeparatorMenuItem();
$filemenu->append($sep);
These lines create a separator. It is used to put menu items into logical groups.

Menus group commands that we can use in application. Toolbars provide a quick access to the most frequently used commands.


Simple toolbar

Next we create a simple toolbar. A toolbar provides a quick access to the most frequently used functionality of an application.
<?php

/* 
 
PHP GTK tutorials
website: http://phpgtktutorials.blogspot.in/
 
*/

class Example extends GtkWindow { 
     

    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();

    } 

    public function init_ui() {

        $this->set_title('Toolbar');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 

        $toolbar = new GtkToolbar();
        $toolbar->set_toolbar_style(Gtk::TOOLBAR_ICONS);

        $newtb = GtkToolButton::new_from_stock(Gtk::STOCK_NEW);
        $opentb = GtkToolButton::new_from_stock(Gtk::STOCK_OPEN);
        $savetb = GtkToolButton::new_from_stock(Gtk::STOCK_SAVE);
        $sep = new GtkSeparatorToolItem();
        $quittb = GtkToolButton::new_from_stock(Gtk::STOCK_QUIT);

        $toolbar->insert($newtb, 0);
        $toolbar->insert($opentb, 1);
        $toolbar->insert($savetb, 2);
        $toolbar->insert($sep, 3);
        $toolbar->insert($quittb, 4);
        
        $quittb->connect_simple("clicked", array('Gtk', 'main_quit'));

        $vbox = new GtkVBox(false, 2);
        $vbox->pack_start($toolbar, false, false, 0);

        $this->add($vbox);

        $this->set_default_size(250, 200); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();         
    }
} 
     
new Example(); 
Gtk::main();
?>
The example shows a toolbar and four tool buttons.
$toolbar = new GtkToolbar();
GtkToolbar widget is created.
$toolbar->set_toolbar_style(Gtk::TOOLBAR_ICONS);
On toolbar, we show only icons. No text.
$newtb = GtkToolButton::new_from_stock(Gtk::STOCK_NEW);
GtkToolButton with an image from stock is created. The image comes from the built-in stock of images.
$sep = new GtkSeparatorToolItem();
This is a separator. It can be used to put toolbar buttons into logical groups.
$toolbar->insert($newtb, 0);
$toolbar->insert($opentb, 1);
...
Toolbar buttons are inserted into the toolbar widget. The first parameter of theinsert() method is the tool button. The second is the position on the toolbar.







Using Widgets PHP GTK

|
Widgets are basic building blocks of a GUI application. Over the years, several widgets became a standard in all toolkits on all OS platforms. For example a button, a check box or a scroll bar. The GTK toolkit's philosophy is to keep the number of widgets at a minimum level. More specialized widgets are created as custom GTK widgets.

GtkCheckButton

GtkCheckButton is a widget, that has two states. On and Off. The On state is visualized by a check mark. It is used to denote some boolean property.
<?php
/* 

 
PHP GTK tutorials

website: http://phpgtktutorials.blogspot.in/

 
*/

 
class Example extends GtkWindow { 
     

    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();

    } 

    private function init_ui() {

        $this->set_title('Check button');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 

        $fixed = new GtkFixed();
        $this->add($fixed);
        
        $cb = new GtkCheckButton("Show title");
        $cb->set_active(true);
        $cb->connect('clicked', array($this, 'on_clicked'));
        $fixed->put($cb, 50, 50);     

        $this->set_default_size(250, 200); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();         
    }

    public function on_clicked($sender) {

        if ($sender->get_active()) {
            $this->set_title("Check button");
        } else {
            $this->set_title("");
        }         
    }
} 
     
new Example(); 
Gtk::main();


?>

We will display a title in the titlebar of the window, depending on the state of theGtkCheckButton.
$cb = new GtkCheckButton("Show title");
The GtkCheckButton widget is created. The constructor of the widget takes one parameter, a label. The label is shown next to the check box.
$cb->set_active(true);
The title is visible by default, so we check the check button by default.
$cb->connect('clicked', array($this, 'on_clicked'));
If we click on the check box widget a clicked signal is emitted. We hook the on_clicked() method to the signal.
if ($sender->get_active()) {
    $this->set_title("Check button");
} else {
    $this->set_title("");
}     
We show the title, if the button is checked. The get_active() method is used to determine the state of the check button. The set_title() method is used to set the title of the window. To clear the title of the window, we use an empty string.
Figure: GtkCheckButton


GtkLabel

The GtkLabel widget shows text. No user interaction is available with this widget.
<?php
/* 

 
PHP GTK tutorials

website: http://phpgtktutorials.blogspot.in/

 
*/

 
class Example extends GtkWindow { 
     

    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();
    } 

    private function init_ui() {

        // no trailing white space!
        $lyrics = "
In this blog, you will learn the basics of GUI programming in GTK with PHP language.
The blog's information is appropriate for beginners.";

        $this->set_title('GtkLabel');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 

        $this->set_border_width(10);
        $label = new GtkLabel($lyrics);
        $this->add($label);

        $this->set_default_size(250, 200); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();         
    }
} 
     
new Example(); 
Gtk::main(); 


?>


The code example shows some lyrics on the window.
// no trailing white space!
    $lyrics = <<<LYRICS
Meet you downstairs in the bar and heard
your rolled up sleeves and your skull t-shirt
We create a multi-line text. In PHP, a multi-line text can be created using the heredoc syntax.
$this->set_border_width(10);
The GtkLabel is surrounded by some empty space.
$label = new GtkLabel($lyrics);
$this->add($label);
The GtkLabel widget is created and added to the window.

GtkEntry

The GtkEntry is a single line text entry field. This widget is used to enter textual data.
<?php

/* 

 
PHP GTK tutorials

website: http://phpgtktutorials.blogspot.in/

 
*/

 
class Example extends GtkWindow { 
     
    private $label;

    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();

    } 

    private function init_ui() {

        $this->set_title('GtkEntry');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 

        $fixed = new GtkFixed();              

        $this->label = new GtkLabel("...");
        $fixed->put($this->label, 60, 40);

        $entry = new GtkEntry();
        $fixed->put($entry, 60, 100);
        $entry->connect('key_release_event', array($this, 'on_key_release'));

        $this->add($fixed); 

        $this->set_default_size(250, 200); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();         
    }

    public function on_key_release($sender, $event) {

        $this->label->set_text($sender->get_text());
    }
} 
     
new Example(); 
Gtk::main();

?>

This example shows an entry widget and a label. The text that we key in the entry is displayed immediately in the label widget.
$entry = new GtkEntry();
GtkEntry widget is created.
$entry->connect('key_release_event', array($this, 'on_key_release'));
We plug the the on_key_release() method to the key_release_event of the GtkEntrywidget.
public function on_key_release($sender, $event) {

    $this->label->set_text($sender->get_text());
}
Inside the method, we get the text from the GtkEntry widget via the get_text()method and set it to the label using the set_text() method of the label.

GtkImage

The GtkImage widget shows an image.
<?php

/* 

 
PHP GTK tutorials

website: http://phpgtktutorials.blogspot.in/

 
*/

 
class Example extends GtkWindow { 
     

    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();

    } 

    private function init_ui() {

        $this->set_title('Red Rock');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 
        
        $this->set_border_width(2);
        $image = GtkImage::new_from_file("redrock.png");                        
        $this->add($image);

        $this->set_default_size(250, 200); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();         
    }
} 
     
new Example(); 
Gtk::main();


?>

In our example, we show an image on the window.
$this->set_border_width(2);
We put some empty border around the image.
$image = GtkImage::new_from_file("redrock.png");
The GtkImage widget is created. We load the image from the file using the staticnew_from_file() method. If the file isn't found or can't be loaded, the resulting GtkImage will display a broken image icon.
$this->add($image);
Widget is added to the container.

GtkComboBox

ComboBox is a widget that allows the user to choose from a list of options.
<?php
/* 

 
PHP GTK tutorials

website: http://phpgtktutorials.blogspot.in/

 
*/

class Example extends GtkWindow { 
     
    private $label;

    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();

    } 

    private function init_ui() {

        $this->set_title('GtkComboBox');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 
        
        $fixed = new GtkFixed();
        $this->label = new GtkLabel('-');
        $fixed->put($this->label, 50, 140);

        $cb = GtkComboBox::new_text();
        $cb->connect('changed', array($this, 'on_changed'));
        
        $cb->append_text('Ubuntu');
        $cb->append_text('Mandriva');
        $cb->append_text('Redhat');
        $cb->append_text('Gentoo');
        $cb->append_text('Mint');

        $fixed->put($cb, 50, 30);

        $this->add($fixed);

        $this->set_default_size(250, 200); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();         
    }

    public function on_changed($sender) {
        $this->label->set_label($sender->get_active_text());
    }
} 
     
new Example(); 
Gtk::main();


?>

The example shows a combo box and a label. The combo box has a list of five options. These are the names of Linux Distros. The label widget shows the selected option from the combo box.
$cb = GtkComboBox::new_text();
The GtkComboBox widget is created. The new_text() is a method, that creates aGtkComboBox just displaying strings.
$cb->append_text('Ubuntu');
$cb->append_text('Mandriva');
$cb->append_text('Redhat');
$cb->append_text('Gentoo');
$cb->append_text('Mint');
It is filled with data.
public function on_changed($sender) {
    $this->label->set_label($sender->get_active_text());
}
Inside the on_changed() method, we get the selected text out of the combo box and set it to the label.


Figure: GtkComboBox



How to lay out our widgets in PHP GTK

|
In this post, we will describe layout management of widgets in windows or dialogs. When we design the GUI of our application, we decide what widgets we will use and how we will organize those widgets in the application. To organize our widgets, we use specialized non visible widgets called layout containers. In this chapter, we will mention GtkAlignmentGtkFixedGtkVBox and GtkTable.

GtkFixed

The GtkFixed container places child widgets at fixed positions and with fixed sizes. This container performs no automatic layout management. In most applications, we don't use this container. There are some specialized areas, where we use it. For example games, specialized applications that work with diagrams, resizable components that can be moved (like a chart in a spreadsheet application), small educational examples.
<?php
/* 

PHP GTK tutorials
website: http://phpgtktutorials.blogspot.in/

*/

class Example extends GtkWindow { 
     

    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();

    } 

    public function init_ui() {

        $this->set_title('Fixed');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 

        $this->modify_bg(Gtk::STATE_NORMAL, new GdkColor(6400, 6400, 6440));

        $bardejov = GtkImage::new_from_file("bardejov.jpg");
        $rotunda = GtkImage::new_from_file("rotunda.jpg");
        $mincol = GtkImage::new_from_file("mincol.jpg");
        
        $fixed = new GtkFixed();
        $fixed->put($bardejov, 20, 20);
        $fixed->put($rotunda, 40, 160);
        $fixed->put($mincol, 170, 50);

        $this->add($fixed);        


        $this->set_default_size(300, 280); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();         
 
    }
} 
     
new Example(); 
Gtk::main();

?>
In our example, we show three small images on the window. We explicitly specify the x, y coordinates, where we place these images.
$this->modify_bg(Gtk::STATE_NORMAL, new GdkColor(6400, 6400, 6440));
For better visual experience, we change the background color to dark gray.
$bardejov = GtkImage::new_from_file("bardejov.jpg");
The GtkImage is a widget, that is used to display images. The picture is loaded from the file on the disk.
$fixed = new GtkFixed();
We create the GtkFixed container.
$fixed->put($bardejov, 20, 20);
We place the first image at x=20, y=20 coordinates.
w.add(fixed);
Finally, we add the GtkFixed container to the Window.


 Figure: Fixed

Buttons

In this code example, we will use a vertical box, a horizontal box and an alignment widget. A horizontal box arranges widgets in a single row. Similarly, a vertical box places its widgets in one column. The Alignment container controls the alignment and the size of its child widget.
<?php

/* 

PHP GTK tutorials
website: http://phpgtktutorials.blogspot.in/

*/

class Example extends GtkWindow { 
     

    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();

    } 

    public function init_ui() {

        $this->set_title('Buttons');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 
        $this->set_border_width(3);

        $vbox = new GtkVBox(false, 5);
        $hbox = new GtkHBox(true, 3);

        $frame = new GtkFrame();
        $vbox->pack_start($frame, true, true, 0);

        $okButton = new GtkButton("OK");
        $okButton->set_size_request(70, 30);
        $closeButton = new GtkButton("Close");

        $hbox->add($okButton);
        $hbox->add($closeButton);
        
        $halign = new GtkAlignment(1, 0, 0, 0);
        $halign->add($hbox);
        $vbox->pack_start($halign, false, false, 3);

        $this->add($vbox);        

        $this->set_default_size(260, 150); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();          
    }
} 
     
new Example(); 
Gtk::main();

?>
In the code example, we place two buttons into the right bottom corner of the window. To accomplish this, we use one horizontal box and one vertical box and one alignment container.
$vbox = new GtkVBox(false, 5);
A vertical box container is created. We set the homogeneous member to false. This means that widgets put into the vertical box will hot have the same size. The vertical spacing between widgets is set to 5 pixels.
$frame = new GtkFrame();
Here we create a GtkFrame widget. The purpose of this widget is to take up space above the two buttons.
$vbox->pack_start($frame, true, true, 0);
Here we place the frame widget into the vertical box. The first parameter of the method is the widget, which is being placed into the box. The following three parameters are expand, fill and padding. The expand parameter is set to true, which means that free space will be allocated around the widget. When the fill parameter is set to true, the widget actually takes up all the free space around it. There is no padding around the child widget.
$hbox = new GtkHBox(true, 3);  
This code line creates a horizontal box. All widgets inside the box will have the same size. There will be 3px space between the widgets horizontally.
$okButton = new GtkButton("OK");
$okButton->set_size_request(70, 30);
$closeButton = new GtkButton("Close");

$hbox->add($okButton);
$hbox->add($closeButton);
We create two buttons and put them inside the horizontal box.
$halign = new GtkAlignment(1, 0, 0, 0);
$halign->add($hbox);
$vbox->pack_start($halign, false, false, 3);
This will create an alignment container that will place its child widget to the right. The xalign member set to 1.0 will put all free space to the left of the horizontal box. This will push the two buttons to the right. We add the horizontal box into the alignment container and pack the alignment container into the vertical box. We must keep in mind that the alignment container takes only one child widget. That's why we must use the horizontal box.

Figure: Buttons

Calculator skeleton

The GtkTable widget arranges widgets in rows and columns.
<?php
class Example extends GtkWindow { 
     

    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();

    } 

    public function init_ui() {

        $this->set_title('Calculator');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 

        $vbox = new GtkVBox(false, 2);

        $mb = new GtkMenubar();
        $filemenu = new GtkMenu();
        $filemi = new GtkMenuItem("File");
        $filemi->set_submenu($filemenu);
        $mb->append($filemi);

        $vbox->pack_start($mb, false, false, 0);

        $table = new GtkTable(5, 4, true);

        $table->attach_defaults(new GtkButton("Cls"), 0, 1, 0, 1);
        $table->attach_defaults(new GtkButton("Bck"), 1, 2, 0, 1);
        $table->attach_defaults(new GtkLabel(), 2, 3, 0, 1);
        $table->attach_defaults(new GtkButton("Close"), 3, 4, 0, 1);

        $table->attach_defaults(new GtkButton("7"), 0, 1, 1, 2);
        $table->attach_defaults(new GtkButton("8"), 1, 2, 1, 2);
        $table->attach_defaults(new GtkButton("9"), 2, 3, 1, 2);
        $table->attach_defaults(new GtkButton("/"), 3, 4, 1, 2);

        $table->attach_defaults(new GtkButton("4"), 0, 1, 2, 3);
        $table->attach_defaults(new GtkButton("5"), 1, 2, 2, 3);
        $table->attach_defaults(new GtkButton("6"), 2, 3, 2, 3);
        $table->attach_defaults(new GtkButton("*"), 3, 4, 2, 3);

        $table->attach_defaults(new GtkButton("1"), 0, 1, 3, 4);
        $table->attach_defaults(new GtkButton("2"), 1, 2, 3, 4);
        $table->attach_defaults(new GtkButton("3"), 2, 3, 3, 4);
        $table->attach_defaults(new GtkButton("-"), 3, 4, 3, 4);

        $table->attach_defaults(new GtkButton("0"), 0, 1, 4, 5);
        $table->attach_defaults(new GtkButton("."), 1, 2, 4, 5);
        $table->attach_defaults(new GtkButton("="), 2, 3, 4, 5);
        $table->attach_defaults(new GtkButton("+"), 3, 4, 4, 5);

        $vbox->pack_start(new GtkEntry(), false, false, 0);
        $vbox->pack_end($table, true, true, 0);

        $this->add($vbox);        

        $this->set_default_size(300, 250); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();         
 
    }
} 
     
new Example(); 
Gtk::main();
?>
We use the GtkTable widget to create a calculator skeleton.
$table = new GtkTable(5, 4, true);
We create a table widget with 5 rows and 4 columns. The third parameter is the homogenous parameter. If set to true, all the widgets in the table are of the same size. The size of all widgets is equal to the largest widget in the table container.
$table->attach_defaults(new GtkButton("Cls"), 0, 1, 0, 1);
We attach a button to the table container. To the top-left cell of the table. The first two parameters are the left and right sides of the cell, the last two parameters are the top and left sides of the cell.
$vbox->pack_end($table, true, true, 0);
We pack the table widget into the vertical box.

Figure: Calculator skeleton

Windows

Next we will create a more advanced example. We show a window, that can be found in the JDeveloper IDE.
<?php

/* 

PHP GTK tutorials
website: http://phpgtktutorials.blogspot.in/

*/

class Example extends GtkWindow { 
     

    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();
    } 

    public function init_ui() {

        $this->set_title('Windows');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 

        $this->set_border_width(15);

        $table = new GtkTable(8, 4, false);
        $table->set_col_spacings(3);
        
        $title = new GtkLabel("Windows");
       
        $halign = new GtkAlignment(0, 0, 0, 0);
        $halign->add($title);        
        $table->attach($halign, 0, 1, 0, 1, GTK::FILL, 
            GTK::FILL, 0, 0);
        
        $frame = new GtkFrame();
        $table->attach($frame, 0, 2, 1, 3, GTK::FILL | Gtk::EXPAND,
            GTK::FILL | GTK::EXPAND, 1, 1);

        $activate = new GtkButton("Activate");
        $activate->set_size_request(50, 30);
        $table->attach($activate, 3, 4, 1, 2, GTK::FILL,
            GTK::SHRINK, 1, 1);

        $valign = new GtkAlignment(0, 0, 0, 0);
        $close = new GtkButton("Close");
        $close->set_size_request(70, 30);
        $valign->add($close);
        $table->set_row_spacing(1, 3);
        $table->attach($valign, 3, 4, 2, 3, Gtk::FILL,
            Gtk::FILL | Gtk::EXPAND, 1, 1);

        $halign2 = new GtkAlignment(0, 1, 0, 0);
        $help = new GtkButton("Help");
        $help->set_size_request(70, 30);
        $halign2->add($help);
        $table->set_row_spacing(3, 6);
        $table->attach($halign2, 0, 1, 4, 5, Gtk::FILL,
            Gtk::FILL, 0, 0);
        
        $ok = new GtkButton("OK");
        $ok->set_size_request(70, 30);
        $table->attach($ok, 3, 4, 4, 5, Gtk::FILL,
            Gtk::FILL, 0, 0);

        $this->add($table);        

        $this->set_default_size(300, 250); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();         
    }
} 
     
new Example(); 
Gtk::main();

?>
The code example shows, how we can create a similar window in PHP GTK.
$table = new GtkTable(8, 4, false);
$table->set_col_spacings(3);
The example is based on the GtkTable container. There will be 3px space between columns.
$title = new GtkLabel("Windows");

$halign = new GtkAlignment(0, 0, 0, 0);
$halign->add($title);        
$table->attach($halign, 0, 1, 0, 1, GTK::FILL, 
    GTK::FILL, 0, 0);
This code creates a label, that is aligned to the left. The label is placed in the first row of the first column of the Table container.
$frame = new GtkFrame();
$table->attach($frame, 0, 2, 1, 3, GTK::FILL | Gtk::EXPAND,
    GTK::FILL | GTK::EXPAND, 1, 1);
The frame widget spans two rows and two columns. It will consume all free space around it. Thus, taking the bulk of the area of the window.
$valign = new GtkAlignment(0, 0, 0, 0);
$close = new GtkButton("Close");
$close->set_size_request(70, 30);
$valign->add($close);
$table->set_row_spacing(1, 3);
$table->attach($valign, 3, 4, 2, 3, Gtk::FILL,
    Gtk::FILL | Gtk::EXPAND, 1, 1);
We put the close button next to the frame widget into the fourth column. (we count from zero) We add the button into the alignment widget, so that we can align it to the top.
$halign2 = new GtkAlignment(0, 1, 0, 0);
$help = new GtkButton("Help");
$help->set_size_request(70, 30);
$halign2->add($help);
$table->set_row_spacing(3, 6);
$table->attach($halign2, 0, 1, 4, 5, Gtk::FILL,
    Gtk::FILL, 0, 0);
The help button is placed into the alignment widget, so that it can be left aligned in its table cell. It is placed at the first column, fifth row.
$ok = new GtkButton("OK");
$ok->set_size_request(70, 30);
$table->attach($ok, 3, 4, 4, 5, Gtk::FILL,
    Gtk::FILL, 0, 0);
Finally the ok button. It is placed at the fourth column, fifth row.

Figure: Windows

Introduction to PHP GTK

|
What is GTK?
The GTK is a library for creating graphical user interfaces. The library is created in C programming language. The GTK library is also called the GIMP Toolkit. Originally, the library was created while developing the GIMP image manipulation program. Since then, the GTK became one of the most popular toolkits under Linux and BSD Unix. Today, most of the GUI software in the open source world is created in Qt or in GTK. Language bindings exist for C++, Python, PHP, Perl, Java, C# and other programming languages.


Introduction to PHP GTK
In this part of the PHP GTK programming tutorial, we will introduce the GTK library and create our first programs using the PHP programming language.

The purpose of this tutorial is to get you started with the GTK and PHP. GTK is one of the leading toolkits for creating graphical user interfaces. PHP is a highly popular scripting language used in server-side web development. It can be also used to create command line scripts via PHP CLI, PHP Command Line Interface.

PHP-GTK
PHP-GTK is a language binding for PHP to write GTK applications. PHP-GTK provides an object-oriented interface to GTK classes and functions. The home page for the project is at gtk.php.net. There we find a reference documentation.

In order to run examples, we need to install  PHP-GTK.



Following Examples Based on Linux Operating System

Simple window example
Now that we have successfully installed the PHP-GTK library, we can start with a small example. In this example, we create a simple window. The window is centered on the screen.
<?php
/* 

PHP GTK tutorials
website: http://phpgtktutorials.blogspot.in/

*/

class Example extends GtkWindow { 
     

    public function __construct() { 

        parent::__construct(); 
         

        $this->set_title('Simple'); 
        $this->set_default_size(250, 150); 

        $this->connect_simple('destroy', array('gtk', 'main_quit')); 

        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show(); 
    } 
} 
     
new Example(); 
Gtk::main(); 
?>


This example shows a 250x150 px window in the center of the screen.

class Example extends GtkWindow { 

The Example class is based on the GtkWindow widget.

$this->set_title('Simple'); 

The set_title() method sets a title for the window.

$this->set_default_size(250, 150); 

This line sets a size of the window. It is going to be 250px wide and 150px high.

$this->connect_simple('destroy', array('gtk', 'main_quit')); 

Here we connect the destroy signal to a callback. The main_quit() method quits the application for good. The destroy signal is emitted, when we click on the close button in the titlebar. Or press Alt + F4.

$this->set_position(GTK::WIN_POS_CENTER);

This line centers the window on the screen.

$this->show();

When everything is ready, we show the window on the screen.

new Example(); 
Gtk::main(); 

We set up the application. An infinite loop is created. From this point the application sits and waits for external events from the user or the system. The loop runs until it is terminated.

Figure: Simple



Creating Tooltip example
This example will show a tooltip. A tooltip is a small rectangular window, which gives a brief information about an object. It is usually a GUI component. It is part of the help system of the application.


<?php
/* 

PHP GTK tutorials
website: http://phpgtktutorials.blogspot.in/

*/

class Example extends GtkWindow { 
     

    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();

    } 

    public function init_ui() {

        $this->set_title('Tooltips');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 

        $fixed = new GtkFixed();
        $this->add($fixed);

        $button = new GtkButton("Button");
        $button->set_size_request(80, 35);
        $button->set_tooltip_text("Button widget");

        $fixed->put($button, 50, 50);
        
        $this->set_tooltip_text("Window widget");

        $this->set_default_size(250, 150); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();         
    }
} 
     
new Example(); 
Gtk::main();
?>
The example creates a window. If we hover a mouse pointer over the area of the window, a tooltip pops up.

$this->init_ui();

The creation of the interface is delegated to the init_ui() method.

$fixed = new GtkFixed();
$this->add($fixed);

The GtkFixed is a container widget, that is used to position widgets at absolute coordinates. The second line sets this container for the GtkWindow of the example. A window has one central container.

$button->set_tooltip_text("Button widget");

We set the button's tooltip with the set_tooltip_text() method.

$this->set_tooltip_text("Window widget");

We set a tooltip for the window. The window is accessed through the $thisvariable.

$this->show_all(); 

When there are multiple widgets on the window, we have two options. Either to call show() on all widgets, or to call show_all(), which shows the container and all its children.

Figure: Tooltips

Creating Quit Button example
In the last example of this section, we will create a quit button. When we press this button, the application terminates.
<?php
class Example extends GtkWindow { 
     

    public function __construct() { 

        parent::__construct(); 
         
        $this->init_ui();

    } 

    public function init_ui() {

        $this->set_title('Quit button');         
        $this->connect_simple('destroy', array('gtk', 'main_quit')); 

        $fixed = new GtkFixed();
        $this->add($fixed);

        $button = new GtkButton("Quit");
        $button->set_size_request(80, 35);
        $button->connect_simple('clicked', array('gtk', 'main_quit'));

        $fixed->put($button, 50, 50);
                
        $this->set_default_size(250, 150); 
        $this->set_position(GTK::WIN_POS_CENTER);
        $this->show_all();         
    }
} 
     
new Example(); 
Gtk::main();
?>
Source code of the example.

$button = new GtkButton("Quit");

Here we create a button widget. The parameter of the constructor is the button's label.

$button->set_size_request(80, 35);

We set a size for the button.

$button->connect_simple('clicked', array('gtk', 'main_quit'));

We plug the main_quit() method to the button clicked signal.

$fixed->put($button, 50, 50);

We put the quit button into the fixed container at x=50, y=50.