pythontextpygamecenterbox

Is there a way to center the text below inside the box?


I have a weather display on a Pi using Python and Pygame I have 2 boxes and I am trying to display the wind speed and direction in them this is my code

    pg.draw.rect(screen, (255,255,255), (643, 67, 85, 30), 2)  # draw windspeed box 
if skyData.status == sky.STATUS_OK: 
    ren = font.render("{}°C".format(skyData.tempnow), 1, pg.Color('black'), pg.Color(134,174,230))
else:
    ren = font.render("", 1, pg.Color('black'), pg.Color(185,208,240))
screen.blit(ren, (658*HRES//1600, 84*VRES//900-ren.get_height()//2))


pg.draw.rect(screen, (255,255,255), (872, 67, 116, 30), 2)  # draw wind direction box cardinal + Degrees
if forecastData.status == forecast.STATUS_OK:
    ren = font.render("{} {}°".format(forecastData.wind_direction_cardinal, forecastData.wind_direction), 1, pg.Color('black'), pg.Color(134,174,230))
else:
    ren = font.render("", 1, pg.Color('black'), pg.Color(134,174,230))
screen.blit(ren, (882*HRES//1600, 84*VRES//900-ren.get_height()//2)) 

Works beautifully but the text is never centered If the windspeed is below 10mph the text is to the right and if the direction is N instead of NW or NNW the text is to the left

I'd like the text to center inside the specified boxes is that possible?

This is how they look at present, if the direction changes to say S then the text is completely to the left Box image


Solution

  • Get the bounding rectangle of the text Surface with get_rect and set the center of the rectangle form the center of the box. Use the rectangle to blit the text:

    box = pygame.Rect(643, 67, 85, 30), 2)
    pg.draw.rect(screen, (255,255,255), box , 2)  # draw windspeed box 
    
    if skyData.status == sky.STATUS_OK: 
        ren = font.render("{}°C".format(skyData.tempnow), 1, pg.Color('black'), pg.Color(134,174,230))
    else:
        ren = font.render("", 1, pg.Color('black'), pg.Color(185,208,240))
    
    ren_rect = ren.get_rect(center = box.center)
    screen.blit(ren, ren_rect)
    

    Note, the dest argument for blit can also be a rectnagle.