Gerald Leese
Gerald Leese

Reputation: 415

Updating text in pygame

What am I doing wrong here? I want to update the text of the label to accommodate a player score. I've looked at other examples and added the update method but the text still stays the same.

class Label():
def __init__(self, txt, location, size=(160,30), bg=WHITE, fg=BLACK, font_name="Segoe Print", font_size=12):
    self.bg = bg  
    self.fg = fg
    self.size = size

    self.font = pygame.font.Font(font_name, font_size)
    self.txt = txt
    self.txt_surf = self.font.render(self.txt, 1, self.fg)
    self.txt_rect = self.txt_surf.get_rect(center=[s//2 for s in self.size])

    self.surface = pygame.surface.Surface(size)
    self.rect = self.surface.get_rect(topleft=location) 



def draw(self):
    self.surface.fill(self.bg)
    self.surface.blit(self.txt_surf, self.txt_rect)
    screen.blit(self.surface, self.rect)


def update(self):
    self.txt_surf = self.font.render(self.txt, 1, self.fg)

    self.surface.blit(self.txt_surf, self.txt_rect)

Upvotes: 3

Views: 6549

Answers (1)

skrx
skrx

Reputation: 20478

You can simply assign the current score (convert it into a string first) to the .txt attribute of your label object and then call its update method.

# In the main while loop.
score += 1
label.txt = str(score)
label.update()

I would also just blit the surface in the draw method and update it in the update method.

def draw(self, screen):
    screen.blit(self.surface, self.rect)

def update(self):
    self.surface.fill(self.bg)
    self.txt_surf = self.font.render(self.txt, True, self.fg)
    self.surface.blit(self.txt_surf, self.txt_rect)

Upvotes: 1

Related Questions