Advertisement
here2share

# Tk_bouncing_balls_demo.py

Dec 13th, 2015
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.20 KB | None | 0 0
  1. # Tk_bouncing_balls_demo.py
  2.  
  3. from Tkinter import *
  4. import random
  5. import time
  6.  
  7. class Ball:
  8.     def __init__(self, canvas, color, size):
  9.         self.canvas = canvas
  10.         self.id = canvas.create_oval(10,10,size,size, fill=color)
  11.         self.canvas.move(self.id, 245, 100)
  12.         self.yspeed = random.randrange(1,9)
  13.         self.xspeed = random.randrange(1,9)
  14.         self.yspeed *= random.choice([1,-1])
  15.         self.xspeed *= random.choice([1,-1])
  16.  
  17.     def draw(self):
  18.         self.canvas.move(self.id, self.xspeed, self.yspeed)
  19.         pos = self.canvas.coords(self.id)
  20.         if pos[0] <= 10:
  21.             self.xspeed = random.randrange(1,9)
  22.         elif pos[2] >= 510:
  23.             self.xspeed = -(random.randrange(1,9))
  24.         if pos[1] <= 10:
  25.             self.yspeed = random.randrange(1,9)
  26.         elif pos[3] >= 410:
  27.             self.yspeed = -(random.randrange(1,9))
  28.  
  29. tk = Tk()
  30. tk.title("Bouncing Balls Demo")
  31. canvas = Canvas(tk, width=520, height=420, bd=0)
  32. canvas.pack()
  33.  
  34. ball_list = []
  35. color_list = ['red', 'blue', 'purple', 'yellow', 'orange','green']
  36. for i in range (40):
  37.     color = random.choice(color_list)
  38.     size = random.randrange(20,100)
  39.     ball_list.append(Ball(canvas, color, size))
  40.  
  41. while True:
  42.     try:
  43.         for ball in ball_list:
  44.             ball.draw()
  45.         tk.update()
  46.     except: break
  47.     time.sleep(0.01)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement