I've been working on a few simple animations using Tkinter.
I've written code for a single ball to move around the screen in a random direction and from a random starting position and bounce off the edges of the canvas.
I would like to repeat this for multiple balls without having to individually write code for each ball. I have tried using the statement for n in xrange(5)
but it seems to have no effect. I would like to be able to create multiple balls all starting in random positions and moving in random directions.
Here is my code:
from Tkinter import *
import random
import time
shop_window = Tk()
shop_window.overrideredirect(1)
shop_window.geometry("254x310")
canvas = Canvas(shop_window, width=254, height=310, bg="snow2", bd=0, highlightthickness=0, relief="ridge")
canvas.pack()
x = random.randint(0, 254)
y = random.randint(0, 310)
ball = canvas.create_oval((x-10, y-10, x+10, y+10), fill="saddle brown")
xspeed = random.randint(1, 5)
yspeed = random.randint(1, 5)
while True:
canvas.move(ball, xspeed, yspeed)
pos = canvas.coords(ball)
if pos[3] >= 310 or pos[1] <= 0:
yspeed = -yspeed
if pos[2] >= 254 or pos[0] <= 0:
xspeed = -xspeed
Tk.update(shop_window)
time.sleep(0.025)
pass
Any help would be appreciated!
Here is an OOP approach that creates a collection of
Ball
objects, keeps track of them on the canvas, and updates them at each turn.