2016-03-24 29 views
-2
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() 

這是我到目前爲止的代碼。我似乎無法解決的問題是我需要球移動不同的速度,也有不同的大小。我需要做的最後一步是把球放到最上面,然後從底部回來。所以最終的產品應該是多種尺寸的球,以不同的速度前進到帆布頂部,然後出現在底部。謝謝你的幫助!如何在Tkinter中以變化的速度製作動畫球?

+0

你在'paint()'和'animate()'方法中有錯誤的縮進。你的'for'週期根本不做任何事情。只需在一個選項卡中縮進所有代碼,您希望在'for'循環中執行'for'循環。 – BoltKey

+0

'for'循環不會無所作爲;該程序將不會編譯縮進錯誤。這可能是將代碼粘貼到問題中。 – TigerhawkT3

回答

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)