如何在这些矩形中添加文字?

时间:2015-06-19 20:24:38

标签: python text menu pygame python-3.4

这是我开始用来制作开始菜单的代码。

# we need some colours!!
black = (0,0,0)
white = (255,255,200)
red = (200,0,0)
green = (0, 200, 0)
bright_red = (255, 0 ,0)
bright_green = (0, 255, 0)
bright_white = (255, 255, 255)

def main():
    pygame.init()

    screen = pygame.display.set_mode((600, 600))

    pygame.display.set_caption("CrazyPongMainMenu")

    menu = cMenu(50, 50, 20, 5, "vertical", 100, screen,
                   [("Start Game", 1, None),
                    ("Options",    2, None),
                    ("Exit",       3, None)])

    menu.set_center(True, True)

    menu.set_alignment("center", "center")

    state = 0
    prev_state = 1

    rect_list = []

    pygame.event.set_blocked(pygame.MOUSEMOTION)

    while 1:
      if prev_state != state:
         pygame.event.post(pygame.event.Event(EVENT_CHANGE_STATE, key = 0))
         prev_state = state
      e = pygame.event.wait()

      if e.type == pygame.KEYDOWN or e.type == EVENT_CHANGE_STATE:
         if state == 0:
            rect_list, state = menu.update(e, state)
         elif state == 1:
            print ("Start Game!")
            state = 0
         elif state == 2:
            print ("Options!")
            state = 0
         else:
            print ("Exit!")
            pygame.quit()
            sys.exit()

      if e.type == pygame.QUIT:
         pygame.quit()
         sys.exit()

      mouse = pygame.mouse.get_pos()

      #print(mouse)

      if 200+150 > mouse[0] > 200 and 250+30 > mouse[1] > 250:
          pygame.draw.rect(screen, bright_green,(200, 250, 150, 30))
      else:
          pygame.draw.rect(screen, green,(200, 250, 150, 30))

      if 200+150 > mouse[0] > 200 and 290+21 > mouse[1] > 290:
          pygame.draw.rect(screen, bright_white,(200, 290, 150, 21))
      else:
          pygame.draw.rect(screen, white,(200, 290, 150, 21))

      if 200+150 > mouse[0] > 200 and 318+25 > mouse[1] > 318:
          pygame.draw.rect(screen, bright_red,(200, 318, 150, 25))
      else:
          pygame.draw.rect(screen, red,(200, 318, 150, 25))

      pygame.display.update(rect_list)

if __name__ == ("__main__"):
   main()

我想把文字放到3个矩形上,但我不知道怎么做。如果有人可以告诉我如何将文字放在矩形上,我们将非常感激!

1 个答案:

答案 0 :(得分:1)

查看此堆栈溢出问题: How to add text into a pygame rectangle

特别是这些位:

self.font = pygame.font.SysFont('Arial', 25)

def addText(self):
    self.screen.blit(self.font.render('Hello!', True, (255,0,0)), (200, 100))
    pygame.display.update()

基本上你想要定义一个字体

然后将它blit到屏幕上,渲染采用args(文本,抗锯齿(你想要的是真实的),颜色)

最后更新