Reputation: 22953
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()
Upvotes: 0
Views: 115
Reputation: 22953
The answer to my question is very obvious once I really thought about what was happing. Since I'm calling the method that contains the for-loop in a while loop, the for-loop is being run multiple times. The two solutions I've used for this problem are: 1. setting a limit to how many items can be in the list:
if len(self.rect_list) > 5):
self.rect_list = self.rect_list[:5]
and two; deleting any more elements then a specified number:
if len(self.text_rect_list) > len(self.sub_items):
del self.text_rect_list[:len(self.sub_items)]
Upvotes: 0
Reputation: 1640
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.
Upvotes: 1