Search code examples
pythontextpygame

How do I draw text that's right aligned in Pygame?


I am making a Math-thingy that requires numbers to be drawn to the screen right aligned.

I'm using this function to draw text:

def drawText(text, font, text_col, x, y):
    img = font.render(text, True, text_col)
    screen.blit(img, (x, y))

How do I draw the text right aligned instead of left aligned?

I tried to use Python's .rjust() function for this, but I'm not using a monospaced font.

Is there anyway to possibly either use .rjust() to right align it or possibly something else?


Solution

  • The pygame.Rect object has a set of virtual attributes that can be used to define the position of surfaces and text. Align the text to its right by setting topright:

    def drawText(text, font, text_col, x, y):
        img = font.render(text, True, text_col)
        rect = img.get_rect(topright = (x, y))
        screen.blit(img, rect)
    

    Minimal example

    import pygame
    from pygame.locals import *
    
    pygame.init()
    screen = pygame.display.set_mode((500, 300))
    clock = pygame.time.Clock()
    font = pygame.font.SysFont(None, 32)
    count = 0
    
    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
            
        count += 1
        text_surf = font.render(str(count), True, "black")
        rect = screen.get_rect().inflate(-110, -110)
        
        screen.fill("white")
        pygame.draw.rect(screen, "red", screen.get_rect().inflate(-100, -100), 5)
        screen.blit(text_surf, text_surf.get_rect(topleft = rect.topleft))
        screen.blit(text_surf, text_surf.get_rect(midtop = rect.midtop))
        screen.blit(text_surf, text_surf.get_rect(topright = rect.topright))
        screen.blit(text_surf, text_surf.get_rect(midleft = rect.midleft))
        screen.blit(text_surf, text_surf.get_rect(center = rect.center))
        screen.blit(text_surf, text_surf.get_rect(midright = rect.midright))
        screen.blit(text_surf, text_surf.get_rect(bottomleft = rect.bottomleft))
        screen.blit(text_surf, text_surf.get_rect(midbottom = rect.midbottom))
        screen.blit(text_surf, text_surf.get_rect(bottomright = rect.bottomright))
        pygame.display.flip()
        clock.tick(100)
    
    pygame.quit()
    exit()