Welcome, guest | Sign In | My Account | Store | Cart

This is my first successful attempt at threading in pyGTK.

Suggestions please.

Python, 71 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/python
import threading
import gtk
import random
import time

gtk.gdk.threads_init()

NUM_THREADS = 10

class PyApp(gtk.Window):
    def __init__(self, threads=None):
        super(PyApp, self).__init__()
        
        self.connect("destroy", self.quit)
        self.set_title("pyGTK Threads Example")
        
        vbox = gtk.VBox(False, 4)
        
        self.threads = []
        for i in range(NUM_THREADS + 1):
            pb = gtk.ProgressBar()
            vbox.pack_start(pb, False, False, 0)
            self.threads.append(ProgressThread(pb, random.uniform(0.01, 0.10)))
        
        self.add(vbox)
        self.show_all()
        
    def quit(self, obj):
        for t in self.threads:
            t.stop()
        
        gtk.main_quit()
        
class ProgressThread(threading.Thread):
    def __init__(self, progressbar, step_value):
        threading.Thread.__init__ (self)
        
        self.pb = progressbar
        self.step = step_value
        
        self.stopthread = threading.Event()

    def run(self):
        while not self.stopthread.isSet():
            cur_frac = self.pb.get_fraction()
            new_frac = cur_frac + self.step
            if new_frac > 1.0:
                new_frac = 1.0
            
            gtk.gdk.threads_enter()
            self.pb.set_fraction(new_frac)
            gtk.gdk.threads_leave()
            
            if self.pb.get_fraction() == 1.0:
                break
            
            time.sleep(0.1)
        
    def stop(self):
        self.stopthread.set()
        
if __name__ == "__main__":
    pyapp = PyApp()
    
    for t in pyapp.threads:
        t.start()
    
    gtk.gdk.threads_enter()
    gtk.main()
    gtk.gdk.threads_leave()

2 comments

Originally I created the threads array outside the PyApp class, down in the "__main__" part. I moved it inside the class and forgot to take out the threads=None in the PyApp class constructor.

I think I should have made a start method for the threads inside the PyApp class also.

I got to a winxp machine and it quit working until I wrapped the gtk.main() call in an enter/leave. I found the solution in: http://www.daa.com.au/pipermail/pygtk/2003-August/005626.html