How To Animate Balls With Varying Speeds In Tkinter?
import time, random from tkinter import *  class Box( Frame ):     def __init__( self ):      # __init__ runs when Box() executes            Frame.__init__( self )  # Frame is the
Solution 1:
One solution is to create a custom class that represents one ball. Have the code to move the ball be inside that class. Each ball can then have its own velocity and direction.
Here's a really simple example for a ball that falls. You would need to add logic for bouncing, falling in different directions, etc.
class Ball(object):
    def __init__(self, canvas, x=10, y=10, radius=10, color="red", speed=1):
        self.canvas = canvas
        self.speed = speed
        self.canvas_id = canvas.create_oval(x-radius, y-radius, x+radius, y+radius,
                                            outline=color, fill=color)
    def move(self, on=True):
        self.canvas.move(self.canvas_id, self.speed, self.speed)
You would use this with something like this:
self.canvas = Canvas(...)
self.balls = []
for i in range(10):
    <compute x, y, color, speed, ...>
    ball = Ball(self.canvas, x, y, radius, color, speed)
    self.balls.append(ball)
To animate them, set up a simple loop:
def animate(self):
    for ball in self.balls:
        ball.move()
    self.canvas.after(30, self.animate)
Post a Comment for "How To Animate Balls With Varying Speeds In Tkinter?"