changes by Barry, e.g. font lock & email addresses
[python/dscho.git] / Demo / tkinter / guido / electrons.py
blob5f6c8b589d6c42c5c29b23f4bb2bc9aca3c7cf9a
1 #! /usr/local/bin/python
3 # Simulate "electrons" migrating across the screen.
4 # An optional bitmap file in can be in the background.
6 # Usage: electrons [n [bitmapfile]]
8 # n is the number of electrons to animate; default is 4, maximum 15.
10 # The bitmap file can be any X11 bitmap file (look in
11 # /usr/include/X11/bitmaps for samples); it is displayed as the
12 # background of the animation. Default is no bitmap.
14 # This uses Steen Lumholt's Tk interface
15 from Tkinter import *
19 # The graphical interface
20 class Electrons:
22 # Create our objects
23 def __init__(self, n, bitmap = None):
24 self.n = n
25 self.tk = tk = Tk()
26 self.canvas = c = Canvas(tk)
27 c.pack()
28 width, height = tk.getint(c['width']), tk.getint(c['height'])
30 # Add background bitmap
31 if bitmap:
32 self.bitmap = c.create_bitmap(width/2, height/2,
33 {'bitmap': bitmap,
34 'foreground': 'blue'})
36 self.pieces = {}
37 x1, y1, x2, y2 = 10,70,14,74
38 for i in range(n,0,-1):
39 p = c.create_oval(x1, y1, x2, y2,
40 {'fill': 'red'})
41 self.pieces[i] = p
42 y1, y2 = y1 +2, y2 + 2
43 self.tk.update()
45 def random_move(self,n):
46 for i in range(1,n+1):
47 p = self.pieces[i]
48 c = self.canvas
49 import rand
50 x = rand.choice(range(-2,4))
51 y = rand.choice(range(-3,4))
52 c.move(p, x, y)
53 self.tk.update()
54 # Run -- never returns
55 def run(self):
56 while 1:
57 self.random_move(self.n)
58 self.tk.mainloop() # Hang around...
60 # Main program
61 def main():
62 import sys, string
64 # First argument is number of pegs, default 4
65 if sys.argv[1:]:
66 n = string.atoi(sys.argv[1])
67 else:
68 n = 30
70 # Second argument is bitmap file, default none
71 if sys.argv[2:]:
72 bitmap = sys.argv[2]
73 # Reverse meaning of leading '@' compared to Tk
74 if bitmap[0] == '@': bitmap = bitmap[1:]
75 else: bitmap = '@' + bitmap
76 else:
77 bitmap = None
79 # Create the graphical objects...
80 h = Electrons(n, bitmap)
82 # ...and run!
83 h.run()
86 # Call main when run as script
87 if __name__ == '__main__':
88 main()