有没有办法让下面的文本在框内居中?

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

我使用 Python 和 Pygame 在 Pi 上显示天气 我有 2 个盒子,我试图在其中显示风速和风向 这是我的代码

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

工作精美,但文本从未居中 如果风速低于 10 英里/小时,文本在右边,如果方向是 N 而不是 NW 或 NNW,文本在左边

我希望文本在指定的框内居中 这可能吗?

这是他们目前的样子,如果方向变成说 S,那么文本完全向左 Box image

获取文本 Surfaceget_rect 的边界矩形,并将矩形的中心设置为框的中心。使用矩形 blit 文本:

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)

请注意,blitdest 参数也可以是矩形。