如何将文本添加到 pygame 矩形中 您所在的位置:网站首页 pygame加载图片代码 如何将文本添加到 pygame 矩形中

如何将文本添加到 pygame 矩形中

2023-03-24 16:14| 来源: 网络整理| 查看: 265

回答问题

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

感谢您的时间。

Answers

您首先必须创建一个Font(或SysFont)对象。在此对象上调用render方法将返回带有给定文本的Surface,您可以在屏幕上或任何其他[Surfacez000018 zw1 上进行 blit。

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的结果,因为这是一个非常慢的操作。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有