Michele Simionato michele.simionato at gmail.com
Sun Apr 9 18:39:11 CEST 2006

```Recently I downloaded Python 2.5a1 and I have started playing with it. In
doing so,
I have been looking at the Demo directory in the distribution, to check if
demos
of the new features have been added there. So, I rediscovered brownian.py,
in Demo/tkinter/guido. I just love this little program, because it reminds
myself
of one my first programs, a long long time ago (a brownian motion in
AmigaBasic,
with sprites!). It is also one of the first programs I looked at, when I
started
studying threads four years ago and I thought it was perfect. However,
I know better and I have realized that brownian.py is perfect textbook example
of a case where you don't really need threads, and you can use generators
So I thought it would be nice to add a threadless version of brownian.py in
the Demo directory.
Here it is. If you like it, I donate the code to the PSF!

----------------------------

# Brownian motion -- an example of a NON multi-threaded Tkinter program ;)

from Tkinter import *
import random
import sys

WIDTH = 400
HEIGHT = 300
SIGMA = 10
BUZZ = 2
LAMBDA = 10
FILL = 'red'

stop = 0                                # Set when main loop exits
root = None                             # main window

def particle(canvas):                   # particle = iterator over the moves
x = random.gauss(WIDTH/2.0, SIGMA)
y = random.gauss(HEIGHT/2.0, SIGMA)
p = canvas.create_oval(x-r, y-r, x+r, y+r, fill=FILL)
while not stop:
dx = random.gauss(0, BUZZ)
dy = random.gauss(0, BUZZ)
try:
canvas.move(p, dx, dy)
except TclError:
break
else:
yield None

def move(particle): # move the particle at random time
particle.next()
dt = random.expovariate(LAMBDA)
root.after(int(dt*1000), move, particle)

def main():
global root, stop
root = Tk()
canvas = Canvas(root, width=WIDTH, height=HEIGHT)
canvas.pack(fill='both', expand=1)
np = 30
if sys.argv[1:]:
np = int(sys.argv[1])
for i in range(np):                  # start the dance
move(particle(canvas))
try:
root.mainloop()
finally:
stop = 1

if __name__ == '__main__':
main()

```