Search code examples
textfontspygamerenderbold

Make a Single Word Within a String Bold


Given the following code (from this answer: How to display text in pygame?):

pygame.font.init() # you have to call this at the start, 
                   # if you want to use this module.
my_font = pygame.font.SysFont('Comic Sans MS', 30)
text_surface = my_font.render('Some Text', False, (0, 0, 0))

Is it possible to make the word 'Text' bold while keeping the word 'Some ' regular?

(without rendering multiple times)


Solution

  • No it is not possible. You must use the "bold" version of the font. "bold" isn't a flag or attribute, it's just a different font. So you need to render the word "Text" with one font and the word "Some" with another font.
    You can use pygame.font.match_font() to find the path to a specific font file.

    Minimal example:

    import pygame
    
    pygame.init()
    window = pygame.display.set_mode((400, 200))
    clock = pygame.time.Clock()
    
    courer_regular = pygame.font.match_font("Courier", bold = False)
    courer_bold = pygame.font.match_font("Courier", bold = True)
    
    font = pygame.font.Font(courer_regular, 50)
    font_b = pygame.font.Font(courer_bold, 50)
    text1 = font.render("Some ", True, (255, 255, 255))
    text2 = font_b.render("Text", True, (255, 255, 255))
    
    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False 
    
        window.fill(0)
        window.blit(text1, (50, 75))
        window.blit(text2, (50 + text1.get_width(), 75))
        pygame.display.flip()
        clock.tick(60)
    
    pygame.quit()
    exit()
    

    With the pygame.freetype modle the text can be rendered with different styles like STYLE_DEFAULT and STYLE_STRONG. However, the text can only be rendered with one style at a time. So you still have to render each word separately:

    import pygame
    import pygame.freetype
    
    pygame.init()
    window = pygame.display.set_mode((400, 200))
    clock = pygame.time.Clock()
    
    ft_font = pygame.freetype.SysFont('Courier', 50)
    text1, rect1 = ft_font.render("Some ", 
        fgcolor = (255, 255, 255), style = pygame.freetype.STYLE_DEFAULT)
    text2, rect2 = ft_font.render("Text", 
        fgcolor = (255, 255, 255), style = pygame.freetype.STYLE_STRONG)
    
    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False 
    
        window.fill(0)
        window.blit(text1, (50, 75))
        window.blit(text2, (50 + rect1.width, 75))
        pygame.display.flip()
        clock.tick(60)
    
    pygame.quit()
    exit()
    

    See also Text and font