【发布时间】:2016-07-11 14:01:08
【问题描述】:
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()
这是我到目前为止的代码。我似乎无法解决的问题是我需要球以不同的速度移动并且也有不同的大小。我需要做的最后一步是让球到达顶部并从底部返回。所以最终的产品应该是多种尺寸的球,以不同的速度移动到画布的顶部,然后出现在底部。感谢您的帮助!
【问题讨论】:
-
您在
paint()和animate()方法中的缩进错误。你的for循环什么都不做。只需在fors 下的for循环中缩进一个标签即可。 -
for循环不会什么都不做;该程序不会因缩进错误而编译。这可能是从将代码粘贴到问题中。