Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Tk_bouncing_balls_demo.py
- from Tkinter import *
- import random
- import time
- class Ball:
- def __init__(self, canvas, color, size):
- self.canvas = canvas
- self.id = canvas.create_oval(10,10,size,size, fill=color)
- self.canvas.move(self.id, 245, 100)
- self.yspeed = random.randrange(1,9)
- self.xspeed = random.randrange(1,9)
- self.yspeed *= random.choice([1,-1])
- self.xspeed *= random.choice([1,-1])
- def draw(self):
- self.canvas.move(self.id, self.xspeed, self.yspeed)
- pos = self.canvas.coords(self.id)
- if pos[0] <= 10:
- self.xspeed = random.randrange(1,9)
- elif pos[2] >= 510:
- self.xspeed = -(random.randrange(1,9))
- if pos[1] <= 10:
- self.yspeed = random.randrange(1,9)
- elif pos[3] >= 410:
- self.yspeed = -(random.randrange(1,9))
- tk = Tk()
- tk.title("Bouncing Balls Demo")
- canvas = Canvas(tk, width=520, height=420, bd=0)
- canvas.pack()
- ball_list = []
- color_list = ['red', 'blue', 'purple', 'yellow', 'orange','green']
- for i in range (40):
- color = random.choice(color_list)
- size = random.randrange(20,100)
- ball_list.append(Ball(canvas, color, size))
- while True:
- try:
- for ball in ball_list:
- ball.draw()
- tk.update()
- except: break
- time.sleep(0.01)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement