3

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)
Gerald Leese
  • 355
  • 4
  • 13

1 Answers1

1

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)
skrx
  • 19,980
  • 5
  • 34
  • 48
  • Derp I forgot to update Label.txt in the while loop I'm still a novice when working with classes I fogot when using the pygame.text.render() that I was putting the player score into self.txt and not directly into the text.render method. – Gerald Leese Oct 13 '17 at 08:32