Re: Progressbar



On Thursday 15 May 2008, Sandra Derbring wrote:
>
> I have a problem with a progressbar. I want, for every file I look into,
> for the bar to show some progress, so that while you wait for the program
> to finish, the whole time can see the bar moving. When I implement it, all
> that happens is that the bar gets filled first after the program's
> finished. How do I make it show during the process?
>
You need to let GTK get in there and do the showing. At the moment you're not:

> self.progressbar = gtk.ProgressBar()
> self.progressbar.show()
>
> self.step = 1/len(list)
>
> for file in list:
>       self.x += self.step
>       #do smth with file
>       self.progressbar.set_fraction(self.x)

You see, what you have above is some code that "does stuff" and occasionally 
changes the progress bar fraction. But GTK (and all other GUI tool kits) work 
on the principle that "doing stuff" is the important thing for the 
application, so while the set_fraction call marks the progress bar as needing 
to be re-drawn, GTK won't actually spend the necessary time drawing it until 
it gets a chance.

There are two ways to fix this. The "quick hack" is to follow the set_fraction 
call with a call that lets GTK do something. In C, such a call would be:

    g_main_iteration ( FALSE );

This, however, is a hack. The better approach is to modify your code structure 
to fit the GUI model. So rather than iterating over the whole file in one go, 
you'd write a function that processed the next "reasonable sized chunk" of 
the file, set the progress bar, then returned. And at the point where you'd 
normally do the processing, you instead just call g_idle_add to put that 
function into the list of things to do when nothing more important is 
happening. Then GTK will get to respond to the progress bar updates between 
calls of that function.

In actual fact, this is (or at least was) a very common programming technique. 
In the absence of threads or similar, it's the only sensible way to implement 
multi-tasking. In embedded systems (where a "grown up" OS is too much of a 
luxury) this co-operative approach is what we do all the time.


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]