2013-10-01 44 views
5

我已經盡力在pygame中繪製矩形,但是我需要能夠在該矩形中獲得像「Hello」這樣的文本。我怎樣才能做到這一點? (如果你能解釋它,以及那將是非常讚賞感謝信)如何將文本添加到pygame矩形中

這裏是我的代碼:

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與給定的文本,您可以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(); 

enter image description here

請注意,您的代碼似乎有點怪,因爲通常你做的所有圖形中的主循環,而不是事前。另外,當您在程序中大量使用文本時,請考慮緩存Font.render的結果,因爲這是一個非常緩慢的操作。

+0

非常感謝。你是我的救星。 – PythonNovice

+0

你怎樣才能在文本框中包裝?如果你有一個完整的句子,例如.. –

+1

@ChrisNielsen試試這個http://pygame.org/wiki/TextWrap – sloth