7-输入文字
原理
显示文字只要3步:
- 创建字体对象
- 渲染文字
- 显示文字
base_font = pygame.font.Font(None, 32) user_text = ':' ... text_surface = base_font.render(user_text, True, (0, 0, 0)) screen.blit(text_surface, (0, 0))
获取用户键盘输入:
if event.type == pygame.KEYDOWN: if event.key == pygame.K_BACKSPACE: # 处理退格键 <-- user_text = user_text[:-1] else: user_text += event.unicode # 按键对应的字符
注意输入的时候,输入法要切换到英文状态。
案例
文字输入框
用一个矩形框来显示输入的文字,当鼠标点击时,矩形框变成蓝色,可以输入文字。当鼠标点击矩形框外时,矩形框变成灰色,不可以输入文字。
import pygame, sys # 初始化 pygame.init() clock = pygame.time.Clock() screen = pygame.display.set_mode((800, 600)) base_font = pygame.font.Font(None, 32) user_text = '' input_rect = pygame.Rect(100, 100, 140, 32) color_active = pygame.Color('lightskyblue3') color_passive = pygame.Color('gray15') color = color_passive active = False while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: if input_rect.collidepoint(event.pos): active = True else: active = False color = color_active if active else color_passive if event.type == pygame.KEYDOWN: if active: if event.key == pygame.K_BACKSPACE: user_text = user_text[:-1] else: user_text += event.unicode screen.fill((255, 255, 255)) pygame.draw.rect(screen, color, input_rect, 2) text_surface = base_font.render(user_text, True, (0, 0, 0)) screen.blit(text_surface, (input_rect.x + 5, input_rect.y + 5)) input_rect.w = max(100, text_surface.get_width() + 10) pygame.display.flip() clock.tick(60)