#(c) Rory Clune 02/13/2011 # A Bouncing Ball, using python's tkinter library from Tkinter import * from numpy import* import time def drawball (cv,x,y,radius): return cv.create_oval(x+radius, y+radius, x-radius, y-radius, fill='white') def paint(parent,cv): global ball, pos, vel, rad, cr, width, height, dt, g #update the y-component of velocity under gravity oldX, oldY = pos[0], pos[1] vel[1] +=g*(dt*1000) #update the ball's position: pos[0]+=vel[0]*(dt*1000) pos[1]+=vel[1]*dt*1000 + 0.5*g*(dt*1000)*(dt*1000) #check for collision with walls if pos[0]-rad< 0: vel[0] = -vel[0]*cr; vel[1]*=fr; pos[0] = rad elif pos[0]+rad> width: vel[0] = -vel[0]*cr; vel[1]*=fr; pos[0] = width - rad if pos[1]-rad < 0: vel[1] = -vel[1]*cr; vel[0]*=fr; pos[1] = rad elif pos[1]+rad > height: vel[1] = -vel[1]*cr; vel[0]*=fr; pos[1] = height - rad # move the ball cv.move(ball, pos[0]-oldX, pos[1]-oldY) time.sleep(dt) parent.after_idle(paint,parent,cv) #create the "root": root = Tk() root.title("A bouncing ball using tkinter") root.bind('q','exit') # create the drawing canvas and "pack" it width, height = 500, 500 cv = Canvas(root, width=500, height=500, bg='grey') cv.pack() pos = [200, 100]#initial position vel = [3,0]#initial velocity cr,fr, g = 0.8,0.95,0.002#coefficients of restitution and friction, and gravity rad = 25#radius of the ball dt = 0.004#timestep ball = drawball(cv,pos[0],pos[1],rad) #delay the first call to paint by 100ms root.after(100,paint,root,cv) root.mainloop()