1- # An example of a multi-threaded Tkinter program.
1+ # Brownian motion -- an example of a multi-threaded Tkinter program.
22
33from Tkinter import *
44import random
1414LAMBDA = 10
1515FILL = 'red'
1616
17+ stop = 0 # Set when main loop exits
18+
19+ lock = threading .Lock () # Protects the random generator
20+
1721def particle (canvas ):
1822 r = RADIUS
19- x = random .gauss (WIDTH / 2.0 , SIGMA )
20- y = random .gauss (HEIGHT / 2.0 , SIGMA )
23+ lock .acquire ()
24+ try :
25+ x = random .gauss (WIDTH / 2.0 , SIGMA )
26+ y = random .gauss (HEIGHT / 2.0 , SIGMA )
27+ finally :
28+ lock .release ()
2129 p = canvas .create_oval (x - r , y - r , x + r , y + r , fill = FILL )
22- while 1 :
23- dx = random .gauss (0 , BUZZ )
24- dy = random .gauss (0 , BUZZ )
30+ while not stop :
31+ lock .acquire ()
32+ try :
33+ dx = random .gauss (0 , BUZZ )
34+ dy = random .gauss (0 , BUZZ )
35+ dt = random .expovariate (LAMBDA )
36+ finally :
37+ lock .release ()
2538 try :
2639 canvas .move (p , dx , dy )
2740 except TclError :
2841 break
29- dt = random .expovariate (LAMBDA )
3042 time .sleep (dt )
3143
3244def main ():
45+ global stop
3346 root = Tk ()
3447 canvas = Canvas (root , width = WIDTH , height = HEIGHT )
3548 canvas .pack (fill = 'both' , expand = 1 )
@@ -39,6 +52,9 @@ def main():
3952 for i in range (np ):
4053 t = threading .Thread (target = particle , args = (canvas ,))
4154 t .start ()
42- root .mainloop ()
55+ try :
56+ root .mainloop ()
57+ finally :
58+ stop = 1
4359
4460main ()
0 commit comments