Advertisement
Guest User

Endlessly bouncing ball - Python TKinter animation

a guest
Jun 25th, 2011
3,115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | None | 0 0
  1. """
  2. Endlessly bouncing ball - demonstrates animation using Python and TKinter
  3. """
  4. import time
  5.  
  6. # Initial coordinates
  7. x0 = 10.0
  8. y0 = 30.0
  9.  
  10. ball_diameter = 30
  11.  
  12. # Get TKinter ready to go
  13. from Tkinter import *
  14. window = Tk()
  15. canvas = Canvas(window, width=400, height=300, bg='white')
  16. canvas.pack()
  17.  
  18. # Lists which will contain all the x and y coordinates. So far they just
  19. # contain the initial coordinate
  20. x = [x0]
  21. y = [y0]
  22.  
  23. # The velocity, or distance moved per time step
  24. vx = 10.0    # x velocity
  25. vy = 5.0    # y velocity
  26.  
  27. # Boundaries
  28. x_min = 0.0
  29. y_min = 0.0
  30. x_max = 400.0
  31. y_max = 300.0
  32.  
  33. # Generate x and y coordinates for 500 timesteps
  34. for t in range(1, 500):
  35.  
  36.     # New coordinate equals old coordinate plus distance-per-timestep
  37.     new_x = x[t-1] + vx
  38.     new_y = y[t-1] + vy
  39.  
  40.     # If a boundary has been crossed, reverse the direction
  41.     if new_x >= x_max or new_x <= x_min:
  42.         vx = vx*-1.0
  43.  
  44.     if new_y >= y_max or new_y <= y_min:
  45.         vy = vy*-1.0
  46.  
  47.     # Append the new values to the list
  48.     x.append(new_x)
  49.     y.append(new_y)
  50.  
  51. # For each timestep
  52. for t in range(1, 500):
  53.  
  54.     # Create an circle which is in an (invisible) box whose top left corner is at (x[t], y[t])
  55.     canvas.create_oval(x[t], y[t], x[t]+ball_diameter, y[t]+ball_diameter, fill="blue", tag='blueball')
  56.     canvas.update()
  57.  
  58.     # Pause for 0.05 seconds, then delete the image
  59.     time.sleep(0.05)
  60.     canvas.delete('blueball')
  61.  
  62. # I don't know what this does but the script won't run without it.
  63. window.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement