/Demo/tkinter/guido/electrons.py

http://unladen-swallow.googlecode.com/ · Python · 91 lines · 52 code · 17 blank · 22 comment · 15 complexity · 6e7340af9915f2ed237082024001a360 MD5 · raw file

  1. #! /usr/bin/env python
  2. # Simulate "electrons" migrating across the screen.
  3. # An optional bitmap file in can be in the background.
  4. #
  5. # Usage: electrons [n [bitmapfile]]
  6. #
  7. # n is the number of electrons to animate; default is 30.
  8. #
  9. # The bitmap file can be any X11 bitmap file (look in
  10. # /usr/include/X11/bitmaps for samples); it is displayed as the
  11. # background of the animation. Default is no bitmap.
  12. from Tkinter import *
  13. import random
  14. # The graphical interface
  15. class Electrons:
  16. # Create our objects
  17. def __init__(self, n, bitmap = None):
  18. self.n = n
  19. self.tk = tk = Tk()
  20. self.canvas = c = Canvas(tk)
  21. c.pack()
  22. width, height = tk.getint(c['width']), tk.getint(c['height'])
  23. # Add background bitmap
  24. if bitmap:
  25. self.bitmap = c.create_bitmap(width/2, height/2,
  26. bitmap=bitmap,
  27. foreground='blue')
  28. self.pieces = []
  29. x1, y1, x2, y2 = 10,70,14,74
  30. for i in range(n):
  31. p = c.create_oval(x1, y1, x2, y2, fill='red')
  32. self.pieces.append(p)
  33. y1, y2 = y1 +2, y2 + 2
  34. self.tk.update()
  35. def random_move(self, n):
  36. c = self.canvas
  37. for p in self.pieces:
  38. x = random.choice(range(-2,4))
  39. y = random.choice(range(-3,4))
  40. c.move(p, x, y)
  41. self.tk.update()
  42. # Run -- allow 500 movemens
  43. def run(self):
  44. try:
  45. for i in range(500):
  46. self.random_move(self.n)
  47. except TclError:
  48. try:
  49. self.tk.destroy()
  50. except TclError:
  51. pass
  52. # Main program
  53. def main():
  54. import sys, string
  55. # First argument is number of electrons, default 30
  56. if sys.argv[1:]:
  57. n = string.atoi(sys.argv[1])
  58. else:
  59. n = 30
  60. # Second argument is bitmap file, default none
  61. if sys.argv[2:]:
  62. bitmap = sys.argv[2]
  63. # Reverse meaning of leading '@' compared to Tk
  64. if bitmap[0] == '@': bitmap = bitmap[1:]
  65. else: bitmap = '@' + bitmap
  66. else:
  67. bitmap = None
  68. # Create the graphical objects...
  69. h = Electrons(n, bitmap)
  70. # ...and run!
  71. h.run()
  72. # Call main when run as script
  73. if __name__ == '__main__':
  74. main()