Pyt*_*ice 6 python text pygame class drawrectangle
我已经到了在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();
Run Code Online (Sandbox Code Playgroud)
感谢您的时间.
首先必须创建一个Font(或SysFont)对象.render在此对象上调用方法将返回Surface带有给定文本的a,您可以在屏幕上或任何其他文本上进行blit 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();
Run Code Online (Sandbox Code Playgroud)

请注意,您的代码似乎有点奇怪,因为通常您在主循环中执行所有绘制,而不是事先.此外,当您在程序中大量使用文本时,请考虑缓存结果Font.render,因为这是一个非常慢的操作.