You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pygame中始终让文本沿X轴居中显示

How to Center Text Horizontally (Only Allow Vertical Movement)

Got it, let's tweak your function so the text stays perfectly centered along the X-axis, while letting you only adjust its vertical position. Here's the step-by-step fix:

Modified Function

First, here's the updated code that handles automatic horizontal centering:

def display_text(text, color, y, font):
    # Render the text as before
    text_image = font.render(text, False, color)
    # Get the rectangle for the text
    text_rect = text_image.get_rect()
    
    # Get the width of your game window
    screen_width = gameDisplay.get_width()
    
    # Set the text's horizontal center to match the screen's center
    text_rect.centerx = screen_width // 2
    # Keep the vertical position controlled by the y parameter
    text_rect.y = y
    
    # Draw the text to the display
    gameDisplay.blit(text_image, text_rect)

Key Changes Explained

  • Removed the x parameter: Since we're handling horizontal positioning automatically, you no longer need to pass an x value. This prevents accidental manual horizontal adjustments.
  • Calculated screen width: We use gameDisplay.get_width() to get your window's current width (works even if the window is resized later).
  • Centered the text: Setting text_rect.centerx = screen_width // 2 ensures the text's horizontal center lines up with the screen's center, regardless of how long the text is.
  • Preserved vertical control: The y parameter still lets you move the text up and down as needed.

Optional: Keep the x Parameter (For Backward Compatibility)

If you have existing code that still calls the function with an x parameter and don't want to update all those calls, you can keep the x parameter but ignore it:

def display_text(text, color, x, y, font):
    text_image = font.render(text, False, color)
    screen_width = gameDisplay.get_width()
    # Ignore the x parameter, force horizontal centering
    text_rect = text_image.get_rect(centerx=screen_width//2, y=y)
    gameDisplay.blit(text_image, text_rect)

This way, any old calls with x values won't break, but the text will still stay centered.

内容的提问来源于stack exchange,提问作者helpmecode

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:02:33