2017-10-12 33 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

非常感謝 –