如何在pygame rectang中添加文本

2024-06-01 00:27:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经在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();

谢谢你抽出时间。


Tags: fromimportselfeventinitdefdisplaysys
1条回答
网友
1楼 · 发布于 2024-06-01 00:27:45

首先必须创建一个^{}(或^{})对象。在此对象上调用^{}方法将返回具有给定文本的^{},您可以在屏幕或任何其他^{}上闪烁。

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();

enter image description here

注意,您的代码看起来有点奇怪,因为通常您在主循环中完成所有绘图,而不是预先完成。另外,当您在程序中大量使用文本时,请考虑缓存Font.render的结果,因为这是一个非常慢的操作。

相关问题 更多 >