生成多个移动对象中的Tkinter帆布(Generating Multiple Moving Obj

2019-11-04 15:59发布

我一直使用Tkinter的几个简单的动画。

我写的代码单个球在屏幕上移动在随机方向和随机的起始位置和反弹画布的边缘。

我想重复这一过程,多个球,而不必为每个球单独编写代码。 我已经使用语句试图for n in xrange(5) ,但它似乎没有任何效果。 我希望能够创建多个球都开始在随机位置,并在随机方向移动。

这里是我的代码:

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

任何帮助,将不胜感激!

Answer 1:

下面是创建集合的OOP方法Ball对象,跟踪他们的画布上,并在每一轮更新它们。

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()


文章来源: Generating Multiple Moving Objects In The Tkinter Canvas