Mr.Python Mr.Python - 1 year ago 70
Python Question

for loop is run more times then specified.

I have been trying to make a drop down menu in pygame. I have a method that that takes a list of strings and renders them to the screen using a for loop. The for loop is shown below.

spacer = 0
for text in range(5):
spacer += 30
rect = pygame.Rect(0, spacer, 100, 20)
pygame.draw.rect(self.surface, (255, 0, 0), rect)

I appended each rectangle that was created in the for loop to a list
i then printed the list to the screen to see it's contents. The Python IDLE window was spammed with the contents of the list.

The method that contained in the for loop is being called in a second method of another class
. The method in class
is called in a while loop:

while running:
for event in pygame.event.get():
if event.type == pg.QUIT:
running = False

#--------method being called in while loop----------#
#--------method being called in while loop----------#

Answer Source

Every time your menu is rendered, you're appending to menu_items_rect_list. Whatever you put in that list will stay there indefinitely. If you want the list to be empty at the start of the frame, you need to clear it yourself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download