Generating Multiple Moving Objects In The Tkinter

2019-08-31 06:23发布

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!

1条回答
等我变得足够好
2楼-- · 2019-08-31 07:07

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.

import tkinter as tk      # for python 2, replace with import Tkinter as tk
import random


class Ball:

    def __init__(self):
        self.xpos = random.randint(0, 254)
        self.ypos = random.randint(0, 310)
        self.xspeed = random.randint(1, 5)
        self.yspeed = random.randint(1, 5)


class MyCanvas(tk.Canvas):

    def __init__(self, master):

        super().__init__(master, width=254, height=310, bg="snow2", bd=0, highlightthickness=0, relief="ridge")
        self.pack()

        self.balls = []   # keeps track of Ball objects
        self.bs = []      # keeps track of Ball objects representation on the Canvas
        for _ in range(25):
            ball = Ball()
            self.balls.append(ball)
            self.bs.append(self.create_oval(ball.xpos - 10, ball.ypos - 10, ball.xpos + 10, ball.ypos + 10, fill="saddle brown"))
        self.run()

    def run(self):
        for b, ball in zip(self.bs, self.balls):
            self.move(b, ball.xspeed, ball.yspeed)
            pos = self.coords(b)
            if pos[3] >= 310 or pos[1] <= 0:
                ball.yspeed = - ball.yspeed
            if pos[2] >= 254 or pos[0] <= 0:
                ball.xspeed = - ball.xspeed
        self.after(10, self.run)


if __name__ == '__main__':

    shop_window = tk.Tk()
    shop_window.geometry("254x310")
    c = MyCanvas(shop_window)

    shop_window.mainloop()
查看更多
登录 后发表回答