| 1 | #! /usr/bin/env python
|
|---|
| 2 |
|
|---|
| 3 | # Simulate "electrons" migrating across the screen.
|
|---|
| 4 | # An optional bitmap file in can be in the background.
|
|---|
| 5 | #
|
|---|
| 6 | # Usage: electrons [n [bitmapfile]]
|
|---|
| 7 | #
|
|---|
| 8 | # n is the number of electrons to animate; default is 30.
|
|---|
| 9 | #
|
|---|
| 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.
|
|---|
| 13 |
|
|---|
| 14 | from Tkinter import *
|
|---|
| 15 | import random
|
|---|
| 16 |
|
|---|
| 17 |
|
|---|
| 18 | # The graphical interface
|
|---|
| 19 | class Electrons:
|
|---|
| 20 |
|
|---|
| 21 | # Create our objects
|
|---|
| 22 | def __init__(self, n, bitmap = None):
|
|---|
| 23 | self.n = n
|
|---|
| 24 | self.tk = tk = Tk()
|
|---|
| 25 | self.canvas = c = Canvas(tk)
|
|---|
| 26 | c.pack()
|
|---|
| 27 | width, height = tk.getint(c['width']), tk.getint(c['height'])
|
|---|
| 28 |
|
|---|
| 29 | # Add background bitmap
|
|---|
| 30 | if bitmap:
|
|---|
| 31 | self.bitmap = c.create_bitmap(width/2, height/2,
|
|---|
| 32 | bitmap=bitmap,
|
|---|
| 33 | foreground='blue')
|
|---|
| 34 |
|
|---|
| 35 | self.pieces = []
|
|---|
| 36 | x1, y1, x2, y2 = 10,70,14,74
|
|---|
| 37 | for i in range(n):
|
|---|
| 38 | p = c.create_oval(x1, y1, x2, y2, fill='red')
|
|---|
| 39 | self.pieces.append(p)
|
|---|
| 40 | y1, y2 = y1 +2, y2 + 2
|
|---|
| 41 | self.tk.update()
|
|---|
| 42 |
|
|---|
| 43 | def random_move(self, n):
|
|---|
| 44 | c = self.canvas
|
|---|
| 45 | for p in self.pieces:
|
|---|
| 46 | x = random.choice(range(-2,4))
|
|---|
| 47 | y = random.choice(range(-3,4))
|
|---|
| 48 | c.move(p, x, y)
|
|---|
| 49 | self.tk.update()
|
|---|
| 50 |
|
|---|
| 51 | # Run -- allow 500 movemens
|
|---|
| 52 | def run(self):
|
|---|
| 53 | try:
|
|---|
| 54 | for i in range(500):
|
|---|
|
|---|