/Demo/tkinter/guido/brownian2.py

http://unladen-swallow.googlecode.com/ · Python · 55 lines · 46 code · 7 blank · 2 comment · 9 complexity · 7d85f140fae1de96a8e25b60f6d609f5 MD5 · raw file

  1. # Brownian motion -- an example of a NON multi-threaded Tkinter program ;)
  2. # By Michele Simoniato, inspired by brownian.py
  3. from Tkinter import *
  4. import random
  5. import sys
  6. WIDTH = 400
  7. HEIGHT = 300
  8. SIGMA = 10
  9. BUZZ = 2
  10. RADIUS = 2
  11. LAMBDA = 10
  12. FILL = 'red'
  13. stop = 0 # Set when main loop exits
  14. root = None # main window
  15. def particle(canvas): # particle = iterator over the moves
  16. r = RADIUS
  17. x = random.gauss(WIDTH/2.0, SIGMA)
  18. y = random.gauss(HEIGHT/2.0, SIGMA)
  19. p = canvas.create_oval(x-r, y-r, x+r, y+r, fill=FILL)
  20. while not stop:
  21. dx = random.gauss(0, BUZZ)
  22. dy = random.gauss(0, BUZZ)
  23. try:
  24. canvas.move(p, dx, dy)
  25. except TclError:
  26. break
  27. else:
  28. yield None
  29. def move(particle): # move the particle at random time
  30. particle.next()
  31. dt = random.expovariate(LAMBDA)
  32. root.after(int(dt*1000), move, particle)
  33. def main():
  34. global root, stop
  35. root = Tk()
  36. canvas = Canvas(root, width=WIDTH, height=HEIGHT)
  37. canvas.pack(fill='both', expand=1)
  38. np = 30
  39. if sys.argv[1:]:
  40. np = int(sys.argv[1])
  41. for i in range(np): # start the dance
  42. move(particle(canvas))
  43. try:
  44. root.mainloop()
  45. finally:
  46. stop = 1
  47. if __name__ == '__main__':
  48. main()