如何在Tkinter中以不同的速度制作球?

时间:2016-03-24 02:46:36

标签: python canvas tkinter tk

import time, random
from tkinter import *

class Box( Frame ):

   def __init__( self ):      # __init__ runs when Box() executes     
      Frame.__init__( self )  # Frame is the top level component
      self.pack() 
      self.master.title( "Canvas animation" ) 
      self.master.geometry( "400x400" ) # size in pixels
      label = Label(self, text="    Bubbles    ")
      label.grid(row=1, column=1)
      # create Canvas component
      self.myCanvas = Canvas( self ) 
      self.myCanvas.grid(row=2, column=1)
      self.myCanvas.config(bg = 'cyan', height = 350, width = 350)

      self.balls = [] #list of balls belongs to the Box 

      self.paint()

      self.animate()

   def paint( self ):

      #create a list of balls
      for i in range(35):

      x1, y1 = random.randint(35,315), random.randint(35,315)
      x2, y2 = x1 + 30 , y1 + 30 #size


      ballObjectId = self.myCanvas.create_oval\
                     ( x1, y1, x2, y2, fill = '')
      self.balls.append([ballObjectId, x1, y1])

  self.myCanvas.update()   
  print ("paint done")

   def animate( self ):
      #animate the list of balls
      for i in range(1000):
          for i in range(len(self.balls)):

          self.myCanvas.delete(self.balls[i][0])   #delete and redraw to move
          self.balls[i][1] += random.randint(-2,2) #change coordinates
          self.balls[i][2] += random.randint(-10,0)
          x1, y1 = self.balls[i][1], self.balls[i][2]
          x2, y2 = x1 + random.randint(30,31) , y1 + random.randint(30,31)

          self.balls[i][0]=(self.myCanvas.create_oval\
                        ( x1, y1, x2, y2, fill = ''))
          self.myCanvas.update()   


def main():
   Box().mainloop() 

if __name__ == "__main__":
   main()

这是我到目前为止的代码。我似乎无法解决的问题是我需要球以不同的速度移动并且还有不同的尺寸。我需要做的最后一步是让球从顶部向上并从底部返回。因此,最终产品应该是多种尺寸的球,以不同的速度行进到画布的顶部,然后出现在底部。谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

一种解决方案是创建一个代表一个球的自定义类。有移动球的代码在该类内。然后每个球可以有自己的速度和方向。

这是球落下的一个非常简单的例子。你需要为弹跳,向不同方向添加逻辑等等。

class Ball(object):
    def __init__(self, canvas, x=10, y=10, radius=10, color="red", speed=1):
        self.canvas = canvas
        self.speed = speed
        self.canvas_id = canvas.create_oval(x-radius, y-radius, x+radius, y+radius,
                                            outline=color, fill=color)
    def move(self, on=True):
        self.canvas.move(self.canvas_id, self.speed, self.speed)

您可以使用以下内容:

self.canvas = Canvas(...)
self.balls = []
for i in range(10):
    <compute x, y, color, speed, ...>
    ball = Ball(self.canvas, x, y, radius, color, speed)
    self.balls.append(ball)

要为它们设置动画,请设置一个简单的循环:

def animate(self):
    for ball in self.balls:
        ball.move()
    self.canvas.after(30, self.animate)