2013-10-01 4 views
5

파이 게임에서 사각형 그리기까지 왔지만 해당 사각형에 "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(); 

이 시간 내 주셔서 감사합니다.

답변

6

먼저 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(); 
보통이 아닌 사전, 메인 루프에있는 모든 드로잉을 할 수 있기 때문에 코드가 조금 이상한 것 같다

enter image description here

참고. 또한 프로그램에서 텍스트를 많이 사용하는 경우 매우 느린 조작이기 때문에 Font.render의 결과 캐싱을 고려하십시오.

+0

대단히 감사합니다. 너는 나의 구세주 야. – PythonNovice

+0

상자에 텍스트 줄 바꾸기를 어떻게 할 수 있습니까? 예를 들어 문장이 모두있는 경우. –

+1

@ChrisNielsen 시도해보십시오. http://pygame.org/wiki/TextWrap – sloth