如何在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
xparameter: Since we're handling horizontal positioning automatically, you no longer need to pass anxvalue. 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 // 2ensures the text's horizontal center lines up with the screen's center, regardless of how long the text is. - Preserved vertical control: The
yparameter 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
相关产品推荐
相关产品推荐

