如何在pygame中显示文本? [英] How to display text in pygame?

查看:149
本文介绍了如何在pygame中显示文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道在 pygame 中显示文本.
我知道我不能像在常规 Python IDLE 中那样使用打印,但我不知道如何使用.

I can't figure out to display text in pygame.
I know I can't use print like in regular Python IDLE but I don't know how.

import pygame, sys
from pygame.locals import *

BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = ( 255, 0, 0)

pygame.init()
size = (700, 500)
screen = pygame.display.set_mode(size)

DISPLAYSURF = pygame.display.set_mode((400, 300))
pygame.display.set_caption('P.Earth')
while 1: # main game loop
    for event in pygame.event.get():
        if event.type == QUIT:           
            pygame.display.update() 

import time

direction = ''
print('Welcome to Earth')
pygame.draw.rect(screen, RED, [55,500,10,5], 0)
time.sleep(1)

这只是整个程序的开始部分.
如果有一种格式可以让我显示我在 pygame 窗口中输入的文本,那就太好了.因此,我会使用其他东西而不是使用打印.但我不知道那是什么别的东西.当我在 pygame 中运行我的程序时,它不显示任何内容.
我希望程序在 pygame 窗口中运行,而不是在空闲状态下运行.

This is only the beginning part of the whole program.
If there is a format that will allow me to show the text I type in the pygame window that'd be great. So instead of using print I would use something else. But I don't know what that something else is. When I run my program in pygame it doesn't show anything.
I want the program to run in the pygame window instead of it just running in idle.

推荐答案

您可以创建带有文本的表面.为此,请看一下这个简短的示例:

You can create a surface with text on it. For this take a look at this short example:

pygame.font.init() # you have to call this at the start, 
                   # if you want to use this module.
myfont = pygame.font.SysFont('Comic Sans MS', 30)

这会创建一个新对象,您可以在该对象上调用 render 方法.

This creates a new object on which you can call the render method.

textsurface = myfont.render('Some Text', False, (0, 0, 0))

这会创建一个新的表面,上面已经绘制了文本.最后,您可以将文本表面 blit 到主屏幕上.

This creates a new surface with text already drawn onto it. At the end you can just blit the text surface onto your main screen.

screen.blit(textsurface,(0,0))

请记住,每次文本更改时,您都必须重新创建表面才能看到新文本.

Bear in mind, that everytime the text changes, you have to recreate the surface again, to see the new text.

这篇关于如何在pygame中显示文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆