2017-10-12 232 views
1

我在这里做错了什么? 我想更新标签的文字以适应玩家的分数。 我看了其他例子,并添加了更新方法,但文本仍然保持不变。更新pygame中的文本

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) 

回答

0

你可以简单地指定当前得分(它转换成字符串第一)到标签对象的属性.txt,然后调用其update方法。

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

我也只是位块传输表面的draw方法,并在update方法更新。

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) 
+0

DERP我忘了在while循环中我还是个新手与我把球员的比分进入自己的类我使用pygame.text.render(当fogot)工作时更新Label.txt。而不是直接进入text.render方法。 –

+0

非常感谢 –