在Tkinter画布中生成多个运动对象 [英] Generating Multiple Moving Objects In The Tkinter Canvas
问题描述
我一直在使用Tkinter制作一些简单的动画。
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.
我想对多个球重复此操作,而不必为每个球单独编写代码。我试过在xrange(5)中对n使用语句,但是它似乎没有任何作用。我希望能够创建多个从随机位置开始并向随机方向移动的球。
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.
这是我的代码:
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
任何帮助将不胜感激!
推荐答案
这里是一种OOP方法,它创建 Ball
对象的集合,在画布上跟踪它们,并在每次转动时对其进行更新。
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()
这篇关于在Tkinter画布中生成多个运动对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!