GtkClock : a clockwork GtkLabel

This small example show how to extend a widget to add a dynamic behaviour, in this case an enhanced GtkLabel displaying the current time without program intervention.

<?php
# Marc Quinton - September 2006.
#
# a Gtk2 widget extension example
#

class PhpGtkClockLabel extends GtkLabel {
  protected
$label;
  protected
$count;
  protected
$timeout;
  protected
$time_format;

  function
__construct() {
   
parent::__construct();
   
$this->timeout = 1000;              # 1000ms is 1 second
   
$this->time_format = '%X';          # %X - preferred time format

    # update clock label as soon as possible.
   
$this->timeout();
  }

  function
timeout(){
   
$this->display_time();

   
# update clock label next delay
   
Gtk::timeout_add($this->timeout, array($this, 'timeout'));
  }

  function
display_time(){
   
$now = strftime($this->time_format);
   
$this->set_text($now);
  }
}

$win = new GtkWindow();
$win->set_title('clock widget test');
$win->connect_simple('destroy', array('gtk', 'main_quit'));
$win->set_position(Gtk::WIN_POS_CENTER);
$win->set_border_width(10);

$clock = new PhpGtkClockLabel();

$win->add($clock);

$win->show_all();
Gtk::main();
?>