Possible Duplicate:
Python & Pygame: Updating all elements in a list under a loop during iteration
我正在使用Python开发程序并使用Pygame。
这是基本代码的样子:
import pygame ---and other stuff necessary
Class_name():
draw_circle()
--some other functions---
i = 0
clicks = 0
object_list = []
while 1:
screen.blit(background, (0,0))
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN and event.key == K_c:
circle_create = True
circle_list.append(Circle())
if event.type == MOUSEBUTTONDOWN and circle_create == True:
if clicks == 0:
circle_list[i].center()
clicks += 1
if event.type == MOUSEMOTION and clicks == 1 and circle_create == True:
circle_list[i].stretch()
#circle.circle_computation()
if circle_create == True:
circle_list[i].draw_circle()
if clicks == 2:
clicks = 0
i += 1
circle_create = False
pygame.display.update()
因此,基本上,按下键“ c”时会从类中创建一个对象。
该对象被添加到列表中,并且该列表被迭代。
然后,用户按下鼠标和东西以绘制一个圆并根据需要创建任意数量的圆。
我想做的是让对象的draw_circle()函数由循环不断更新,以便为列表中的所有对象显示绘制的圆,但是由于列表是迭代的,因此它会更新添加的新对象和对象已经附加的文件不会更新。
该程序可以正常工作,它可以根据用户输入画圈,但是更新问题是我需要解决的唯一问题。
是否有可能通过while循环更新对象列表中的所有元素?我已经尝试了很多天,但我一直找不到一个好的解决方案。任何想法表示赞赏。谢谢
最佳答案
根据您现有的代码以及您想要画出所有圆圈的愿望,而不仅仅是最近的一个,我认为以下代码更改应会为您提供所需的行为:
#circle.circle_computation()
if circle_create == True:
#circle_list[i].draw_circle()
for j in xrange(i):
circle_list[j].draw_circle()
关于python - 在Python中的循环下访问迭代列表中的所有元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11172444/