Tuesday 18 January 2011

Simple countdown progress bar remake

I've been warned on reddit my countdown progress bar implementation explained here is messy and wouldn't work on Windows OS because changing widgets is valid only from the GUI thread and I must admit, a special thread object for the purpose of updating the widget really looks messy, but I really didn't test it to see if it works on Windows. Today I reworked the code anyway, merging all the previous stuff in one object that builds GUI and acts as a timer at the same time. Also I made some minor improvements. Simple countdown timer is now even more simpler:

 1 import time, gtk 
2 from threading import Thread, Event
3
4 gtk.gdk.threads_init() # initialize threads right away
5
6 class cdProgressBar(Thread):
7 def __init__(self, time = 10):
8 Thread.__init__(self)
9 self.time = self.tot_time = time
10
11 self.builder = gtk.Builder()
12 self.builder.add_from_file('progressbar_countdown.glade')
13 self.window = self.builder.get_object('cd_window')
14 self.progressbar = self.builder.get_object('cd_progressbar')
15 self.set_progressbar()
16
17 self.builder.connect_signals({
18 'on_cd_window_delete_event' : self.quit,
19 'on_cd_startbutton_clicked' : self.startbutton_clicked,
20 'on_cd_pausebutton_clicked' : self.pausebutton_clicked
21 })
22
23 # threading
24 self.unpause = Event()
25 self.restart = False
26 self.setDaemon(True) # stop the thread on exit
27
28 def main(self):
29 self.window.show_all()
30 self.start() # start the thread
31 gtk.main()
32
33 def quit(self, widget, data = None):
34 gtk.main_quit()
35
36 def startbutton_clicked(self, widget, data = None):
37 if not self.unpause.isSet():
38 self.unpause.set()
39 self.restart = True
40
41 def pausebutton_clicked(self, widget, data = None):
42 if self.unpause.isSet():
43 self.unpause.clear() # pause the countdown timer
44 else:
45 self.unpause.set()
46
47 def set_progressbar(self):
48 self.progressbar.set_text(str(self.time))
49 self.progressbar.set_fraction(self.time/float(self.tot_time))
50
51 def run(self):
52 while True:
53 self.unpause.wait() # wait the self.unpause.isSet()
54 if self.restart:
55 self.time = self.tot_time
56 self.restart = False
57 self.set_progressbar()
58 time.sleep(1)
59 if self.time != 0:
60 self.time -= 1
61
62 cd_window = cdProgressBar()
63 cd_window.main()

Countdown Progress Bar is designed using glade interface designer like this. Code is tested and it's working under Windows and under Linux as well.

0 comments: