Search code examples
phpeventsgtkiterationprogram-entry-point

PHP GTK refreshing GUI


I've been trying to make a very simple PHP application using php-gtk. The program does some processing and outputs the status of that process. The problem is that the application doesn't launch until the process is finished. I read that the line while (Gtk::events_pending()) {Gtk::main_iteration();} allows the main loop to continue while processing but it doesn't work for me. Here's the code:

<?php
if(!class_exists('gtk')){
    exit('php-gtk2!!');
}

$wnd = new GtkWindow();
$wnd->set_size_request(400, 200);
$wnd->set_title('test');
$wnd->connect_simple('destroy', array('gtk', 'main_quit'));

$lbl = new GtkLabel('1/3');

function processing($lbl){
    while (Gtk::events_pending()) {Gtk::main_iteration();}
    sleep(2);
    $lbl->set_text('2/3');
    sleep(2);
    $lbl->set_text('3/3');
}

processing($lbl);

$wnd->add($lbl);
$wnd->show_all();
Gtk::main();

?> I tried placing that line everywhere on the code and I'm not sure why it doesn't work. Any help would be really appreciated. Thank you in advance!

(Note: the sleep function is only to simulate some heavy processing)


Solution

  • Since you are trying to do work at the same time as your GUI is running, you will need to use a second thread, communicating from that thread to the GUI thread to get GUI updates. To do this, use the gdk_threads_add_idle() or g_idle_add() functions. Do not call GTK+ functions directly from the other thread!