首页 > 解决方案 > 如何在pygame的屏幕上显示文本

问题描述

我的问题是我想做的就是在 pygame 的屏幕上显示文本。如果有人知道如何做到这一点,请告诉我!

我的代码

import time
import pygame
from pygame.locals import *
pygame.init
blue = (0,0,255)
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
WINDOW = pygame.display.set_mode((WINDOW_WIDTH,WINDOW_HEIGHT))
pygame.display.set_caption("Text")
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit
            exit()
    font = pygame.font.SysFont(None, 25)
    def show_text(msg,color):
        text = font.render(msg,True,color)
        WINDOW.blit(text,[WINDOW_WIDTH/2,WIDTH_HEIGHT/2])
        show_text("This is a message!", blue)
    pygame.display.update()

我只想制作“这是一条消息!”的文字。就这些

标签: textpygame

解决方案


你已经很接近了。要呈现文本,您需要首先定义 a font,然后将其用于render(). 这将创建一个包含文本的位图,该位图需要指向blit()窗口。

所有必要的部分都在问题代码中,它们只是有点混淆。

import time
import pygame
from pygame.locals import *

# Constants
blue = (0,0,255)
WINDOW_WIDTH  = 500
WINDOW_HEIGHT = 500

def show_text( msg, color, x=WINDOW_WIDTH//2, y=WINDOW_WIDTH//2 ):
    global WINDOW
    text = font.render( msg, True, color)
    WINDOW.blit(text, ( x, y ) )

pygame.init()
WINDOW = pygame.display.set_mode((WINDOW_WIDTH,WINDOW_HEIGHT))
pygame.display.set_caption("Text")

# Create the font (only needs to be done once)
font = pygame.font.SysFont(None, 25)

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            exit()

    WINDOW.fill( ( 255, 255, 255 ) )   # fill screen with white background

    show_text("This is a message!", blue)

    pygame.display.update()

推荐阅读