前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Pygame基础7-输入文字

Pygame基础7-输入文字

作者头像
一只大鸽子
发布2024-04-11 13:04:34
970
发布2024-04-11 13:04:34
举报

7-输入文字

原理

显示文字只要3步:

  1. 1. 创建字体对象
  2. 2. 渲染文字
  3. 3. 显示文字
代码语言:javascript
复制
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))

获取用户键盘输入:

代码语言:javascript
复制
if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_BACKSPACE: # 处理退格键 <--
        user_text = user_text[:-1]
    else:
        user_text += event.unicode # 按键对应的字符

注意输入的时候,输入法要切换到英文状态。

案例

文字输入框 用一个矩形框来显示输入的文字,当鼠标点击时,矩形框变成蓝色,可以输入文字。当鼠标点击矩形框外时,矩形框变成灰色,不可以输入文字。

文本框

代码语言:javascript
复制
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)
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2024-03-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 一只大鸽子 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 7-输入文字
    • 原理
      • 案例
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档