Pygame基础7-输入文字

简介: Pygame基础7-输入文字

7-输入文字

原理

显示文字只要3步:

  1. 创建字体对象
  2. 渲染文字
  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)
相关文章
|
Python
pygame将文字转为图片
pygame将文字转为图片
148 0
|
Python
pygame学习笔记(3)——时间、事件、文字
转载请注明:@小五义 http://www.cnblogs.com/xiaowuyi 1、运动速率    上节中,实现了一辆汽车在马路上由下到上行驶,并使用了pygame.time.delay(200)来进行时间延迟。
1029 0
|
2月前
|
存储 人工智能 算法
使用 Python 和 Pygame 制作游戏:第九章到第十章
使用 Python 和 Pygame 制作游戏:第九章到第十章
66 0
使用 Python 和 Pygame 制作游戏:第九章到第十章
|
2月前
|
Python
Python使用pygame播放MP3
Python使用pygame播放MP3
51 0
|
2月前
|
定位技术 Python
【python】pygame实现植物大战僵尸小游戏(附源码 有注释)
【python】pygame实现植物大战僵尸小游戏(附源码 有注释)
903 1
|
24天前
|
开发框架 Python
Python的`pygame`库用于2D游戏开发,涵盖图形、音频和输入处理。
【6月更文挑战第21天】Python的`pygame`库用于2D游戏开发,涵盖图形、音频和输入处理。要开始,先通过`pip install pygame`安装。基本流程包括:初始化窗口、处理事件循环、添加游戏元素(如玩家和敌人)、响应用户输入、更新游戏状态及结束条件。随着项目发展,可逐步增加复杂性。
37 1
|
1月前
|
Python
【Python的魅力】:利用Pygame实现游戏坦克大战——含完整源码
【Python的魅力】:利用Pygame实现游戏坦克大战——含完整源码
|
1月前
|
Linux 开发工具 开发者
Pygame是一个免费且开源的Python库
【6月更文挑战第12天】Pygame是一个免费且开源的Python库
37 3
|
18天前
|
索引 Python
技术好文共享:用Python的Pygame包做飞行棋
技术好文共享:用Python的Pygame包做飞行棋

热门文章

最新文章