微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在pygame中在屏幕上显示文本

如何解决如何在pygame中在屏幕上显示文本

我的问题是我想做的就是在pygame的屏幕上显示文本。如果有人知道该怎么做,请告诉我!

我的代码

import time
import pygame
from pygame.locals import *
pygame.init
blue = (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()

我只想说“这是一条信息!”。就这样

解决方法

您已经很接近了。要渲染文本,您需要首先定义font,然后将其用于render()。这将创建一个带有文本的位图,该位图需要blit()到窗口。

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

import time
import pygame
from pygame.locals import *

# Constants
blue = (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()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。