from Tkinter import * # These are variables I will define as instance variables #xLoc - Where is the ball? (X) #yLoc - Where is the ball? (Y) #xVelocity - How fast is the ball moving (X) #yVelocity - How fast is the bal moving (Y) #color - Color of the ball class Ball: # These are class variables, one copy of these variables are stored among all instances # of this class bouncyness = 0.9 def __init__(self, xLoc, yLoc, xVelocity, yVelocity): self.xLoc = xLoc self.yLoc = yLoc self.xVelocity = xVelocity self.yVelocity = yVelocity # Draw the initial ball def draw(self, canvas): rad = 5 x1 = self.xLoc-rad y1 = self.yLoc-rad x2 = self.xLoc+rad y2 = self.yLoc+rad self.itm = canvas.create_oval(x1, y1, x2, y2, fill='green') print "%d %d %d %d " %(x1, y1, x2, y2) self.canvas = canvas # Update to the new location of the ball def update(self): mod = 5 # The ball isn't bouncing... stop! if abs(self.yVelocity) < 2 and self.yLoc >= 400: self.yVelocity = 0 self.xVelocity = 0 return else: self.yVelocity += 9.8/5 # Bounce off the "floor" if self.yLoc > 400: self.direction *= -1 self.yVelocity = self.yVelocity * self.bouncyness deltaY = int(self.yVelocity*self.direction) self.yLoc += deltaY # Bounce off the "wall" if self.xLoc > 400 or self.xLoc < 0: self.xVelocity *= -1 deltaX = self.xVelocity/5 self.xLoc += deltaX self.canvas.move(self.itm, deltaX, deltaY) # ------------------------------------ # Outside the class # ------------------------------------ def moveIt(): ball.update() canvas.after(20, moveIt) def main(): global ball, canvas root = Tk() canvas = Canvas(root, width=800, height=800) canvas.pack() ball = Ball(30, 30, 10, 30) ball.draw(canvas) canvas.after(1000, moveIt) root.mainloop() main()