Python 如何在pygame中显示文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20842801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:21:43  来源:igfitidea点击:

How to display text in pygame?

pythontextpygame

提问by user3146817

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

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

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)

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 doesnt show anything.
I want the program to run in the pygame window instead of it just running in idle.

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

回答by Bartlomiej Lewandowski

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)

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

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

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

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.

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

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.

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

回答by GhostFrag1

When displaying I sometimes make a new file called Funk. This will have the font, size etc. This is the code for the class:

显示时我有时会创建一个名为 Funk 的新文件。这将具有字体、大小等。这是该类的代码:

import pygame

def text_to_screen(screen, text, x, y, size = 50,
            color = (200, 000, 000), font_type = 'data/fonts/orecrusherexpand.ttf'):
    try:

        text = str(text)
        font = pygame.font.Font(font_type, size)
        text = font.render(text, True, color)
        screen.blit(text, (x, y))

    except Exception, e:
        print 'Font Error, saw it coming'
        raise e

Then when that has been imported when I want to display text taht updates E.G score I do:

然后当我想显示文本 taht 更新 EG 分数时,我会这样做:

Funk.text_to_screen(screen, 'Text {0}'.format(score), xpos, ypos)

If it is just normal text that isn't being updated:

如果只是没有更新的普通文本:

Funk.text_to_screen(screen, 'Text', xpos, ypos)

You may notice {0} on the first example. That is because when .format(whatever) is used that is what will be updated. If you have something like Score then target score you'd do {0} for score then {1} for target score then .format(score, targetscore)

您可能会注意到第一个示例中的 {0}。那是因为当 .format(whatever) 被使用时,它就会被更新。如果你有类似 Score 然后目标分数的东西,你会为分数做 {0} 然后为目标分数做 {1} 然后 .format(score, targetscore)

回答by skrx

There's also the pygame.freetypemodule which is more modern, works with more fonts and offers additional functionality.

还有pygame.freetype一个更现代的模块,可以使用更多字体并提供额外的功能。

Create a font object with pygame.freetype.SysFont()or pygame.freetype.Fontif the font is inside of your game directory.

创建一个字体对象pygame.freetype.SysFont()pygame.freetype.Font如果字体为你的游戏目录内。

You can render the text either with the rendermethod similarly to the old pygame.font.Font.renderor directly onto the target surface with render_to.

您可以使用与render旧方法类似的方法渲染文本,也可以使用pygame.font.Font.render直接将文本渲染到目标表面上render_to

import pygame
import pygame.freetype  # Import the freetype module.


pygame.init()
screen = pygame.display.set_mode((800, 600))
GAME_FONT = pygame.freetype.Font("your_font.ttf", 24)
running =  True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((255,255,255))
    # You can use `render` and then blit the text surface ...
    text_surface, rect = GAME_FONT.render("Hello World!", (0, 0, 0))
    screen.blit(text_surface, (40, 250))
    # or just `render_to` the target surface.
    GAME_FONT.render_to(screen, (40, 350), "Hello World!", (0, 0, 0))

    pygame.display.flip()

pygame.quit()

回答by Shital Shah

This is slighly more OS independent way:

这是一种更独立于操作系统的方式:

# do this init somewhere
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
font = pygame.font.Font(pygame.font.get_default_font(), 36)

# now print the text
text_surface = font.render('Hello world', antialias=True, color=(0, 0, 0))
screen.blit(text_surface, dest=(0,0))