如何在pygame矩形中添加文本

10

我已经在pygame中画了一个矩形,但我需要能够将像“Hello”这样的文本放入该矩形中。我该怎么做?(如果您能解释一下那就更好了。谢谢)

这是我的代码:

import pygame
import sys
from pygame.locals import *

white = (255,255,255)
black = (0,0,0)


class Pane(object):
    def __init__(self):

        pygame.init()
        pygame.display.set_caption('Box Test')
        self.screen = pygame.display.set_mode((600,400), 0, 32)
        self.screen.fill((white))
        pygame.display.update()

    def addRect(self):
        self.rect = pygame.draw.rect(self.screen, (black), (175, 75, 200, 100), 2)
        pygame.display.update()

    def addText(self):
        #This is where I want to get the text from

if __name__ == '__main__':
    Pan3 = Pane()
    Pan3.addRect()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit(); sys.exit();

感谢您的时间。

2个回答

11

首先需要创建一个Font(或SysFont)对象。在该对象上调用render方法将返回一个带有指定文本的Surface,您可以将其绘制到屏幕或任何其他Surface上。

import pygame
import sys
from pygame.locals import *

white = (255,255,255)
black = (0,0,0)


class Pane(object):
    def __init__(self):
        pygame.init()
        self.font = pygame.font.SysFont('Arial', 25)
        pygame.display.set_caption('Box Test')
        self.screen = pygame.display.set_mode((600,400), 0, 32)
        self.screen.fill((white))
        pygame.display.update()


    def addRect(self):
        self.rect = pygame.draw.rect(self.screen, (black), (175, 75, 200, 100), 2)
        pygame.display.update()

    def addText(self):
        self.screen.blit(self.font.render('Hello!', True, (255,0,0)), (200, 100))
        pygame.display.update()

if __name__ == '__main__':
    Pan3 = Pane()
    Pan3.addRect()
    Pan3.addText()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit(); sys.exit();

请注意,你的代码似乎有点奇怪,通常情况下你应该在主循环中完成所有绘图而不是事先。此外,当你在程序中大量使用文本时,请考虑缓存Font.render的结果,因为这是一个非常耗时的操作。


非常感谢。你是我的救星。 - PythonNovice
如何使文本在框中换行?如果您有一个完整的句子,例如... - Chris Nielsen
好的,现在我该如何将矩形和文本添加到Sprite表面上? - Chris Nielsen

0

你好! 说实话,有很好的方法可以在当前矩形的任何位置编写文本。 现在我将展示如何轻松完成它。


首先,我们需要创建矩形实例的对象:

                rect_obj = pygame.draw.rect(
                    screen,
                    color,
                    <your cords and margin goes here>
                )

现在,rect_objpygame.rect 实例的对象。因此,我们可以自由地使用这些方法进行操作。但是,在此之前,让我们像这样创建我们的渲染文本对象:

                text_surface_object = pygame.font.SysFont(<your font here>, <font size here>).render(
                    <text>, True, <color>
                )

毕竟我们可以自由地使用所有方法,就像我之前提到的一样: text_rect = text_surface_object.get_rect(center=rect_obj.center)

这段代码是关于什么的? 我们刚刚获得了当前矩形的中心坐标,非常简单! 现在,您需要像这样绘制屏幕: self.game_screen.blit(text_surface_object, text_rect)


编程愉快!:)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接