Mr.Python Mr.Python - 3 months ago 8
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)
self.rect_list.append(rect)


I appended each rectangle that was created in the for loop to a list
rect_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
Menu
. The method in class
Menu
is called in a while loop:

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

#--------method being called in while loop----------#
Menu_Class_Obj.render_menu()
#--------method being called in while loop----------#
pygame.display.update()

Answer

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.

Comments