【问题标题】:Accessing all elements in an iterated list under a loop in Python [duplicate]在Python中的循环下访问迭代列表中的所有元素[重复]
【发布时间】:2012-06-24 15:26:05
【问题描述】:

可能重复:
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 循环更新对象列表中的所有元素?我已经尝试了很多天,但我无法找到一个好的解决方案。任何想法表示赞赏。谢谢

【问题讨论】:

  • 您现在没有遍历任何列表。而i 始终为 0
  • 'i' 在 'clicks == 2' 时加 1。
  • 我在这段代码中没有看到你增加 i 的任何地方
  • 您是否尝试对 circle_list 中的每个项目调用 center() 方法?
  • center() 为列表中的当前项目调用。假设 i = 2,列表中的第三个元素将为该对象调用 center()。

标签: python list drawing pygame geometry


【解决方案1】:

根据您现有的代码和您声明的绘制所有圆圈的愿望,而不仅仅是最近的一个,我认为以下代码更改应该为您提供您正在寻找的行为:

#circle.circle_computation()
if circle_create == True:
    #circle_list[i].draw_circle()
    for j in xrange(i):
        circle_list[j].draw_circle()

【讨论】:

    猜你喜欢
    • 2023-04-07
    • 2012-06-25
    • 2014-05-02
    • 1970-01-01
    • 2016-09-04
    • 2021-07-13
    • 2020-08-02
    • 1970-01-01
    • 2015-01-17
    相关资源
    最近更新 更多