【发布时间】:2019-02-26 15:29:45
【问题描述】:
如下面的代码所示,当用户点击窗口时,我有一个函数会产生一个圆圈的动画。我的问题是,要让另一个圆圈出现并在一个圆圈已经生成后移动,我必须等待前一个圆圈完成其移动循环。在降雪函数结束时一个圆圈完成其“i in range”循环后,我可以单击并生成另一个圆圈。我希望能够随时单击并让尽可能多的圆圈同时移动(我知道我在函数下的代码中将其限制为 10 次)。看来我需要同时多次运行同一个方法。
from graphics import*
from random import*
win = GraphWin("Graphics Practice", 500, 500)
colours = ["blue", "red", "orange", "purple", "green", "black", "brown", "yellow", "pink"]
def snowfall(randColour):
point = win.getMouse()
circle = Circle(point, 40)
circle.draw(win)
circle.setFill(colours[randColour])
for i in range(1000):
circle.move(0, 1)
time.sleep(0.002)
randColour = randint(0, 8)
for i in range (10):
repeatColour = randColour
snowfall(randColour)
randColour = randint(0, 8)
while randColour == repeatColour:
randColour = randint(0, 8)
win.getMouse()
win.close()
我在多线程方面的一次失败尝试:
from graphics import*
from random import*
win = GraphWin("Graphics Practice", 500, 500)
colours = ["blue", "red", "orange", "purple", "green", "black", "brown", "yellow", "pink"]
def snowfall(randColour):
point = win.getMouse()
circle = Circle(point, 40)
circle.draw(win)
circle.setFill(colours[randColour])
for i in range(1000):
circle.move(0, 1)
time.sleep(0.002)
randColour = randint(0, 8)
t1 = threading.Thread(target = snowfall, args = randColour)
for i in range (10):
repeatColour = randColour
t1.start()
t1.join()
randColour = randint(0, 8)
while randColour == repeatColour:
randColour = randint(0, 8)
win.getMouse()
win.close()
最新代码:
from graphics import*
from random import*
win = GraphWin("Graphics Practice", 500, 500)
colours = ["blue", "red", "orange", "purple", "green", "black", "brown", "yellow", "pink"]
class Snowflake(object):
def __init__(self, randColour):
self.circle = Circle(point, 40)
self.circle.draw(win)
self.circle.setFill(colours[randColour])
def next_frame(self):
self.circle.move(0, 1)
randColour = randint(0, 8)
sprites = []
for i in range (100):
repeatColour = randColour
point = win.getMouse()
sprites.append(Snowflake(randColour))
randColour = randint(0, 8)
while randColour == repeatColour:
randColour = randint(0, 8)
for s in sprites:
while True:
s.next_frame()
time.sleep(0.02)
win.getMouse()
randColour = randint(0, 8)
sprites.append(Snowflake(randColour, point))
win.getMouse()
win.close()
【问题讨论】:
-
尝试在编程中使用多线程希望您的问题会得到解决。
标签: python function loops methods concurrency