【问题标题】:Generating Multiple Moving Objects In The Tkinter Canvas在 Tkinter 画布中生成多个移动对象
【发布时间】:2018-04-07 17:29:03
【问题描述】:

我一直在使用 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

任何帮助将不胜感激!

【问题讨论】:

  • 最佳解决方案涉及面向对象的方法。可以吗,还是要避免使用 OO 方法?
  • @BryanOakley 我对 OO 方法没有任何问题。我之前尝试使用对象来解决问题,但发现它有点棘手,因为我仍处于使用 tkinter 编程的初级阶段。

标签: python animation tkinter canvas tkinter-canvas


【解决方案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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    • 1970-01-01
    • 2018-04-12
    • 2021-09-22
    • 1970-01-01
    相关资源
    最近更新 更多