pygame / python中的文本输入框

时间:2013-05-24 21:43:20

标签: python text input pygame

我正在使用pygame / python中的RPG。我做了一个炭火。允许您自定义播放器的创建者。现在我正在寻找一种方法来提示屏幕上的名称。我不想让它制作一个盒子,只需打印用户在特定区域输入的内容(见图片)。 谢谢你的帮助。

http://ubuntuone.com/3HdzOKroopUEf1YxqNnbFM< -----图片(通过链接只显示蓝色)

3 个答案:

答案 0 :(得分:6)

您可以捕获事件,如果是event.type == KEYDOWN,则检查event.key以获取用户按下的键。然后,您可以将其添加到文本变量并在屏幕上显示。

答案 1 :(得分:2)

您也可以使用EzText。这是一个基本上完成FRJA为您描述的模块。如果你谷歌" pygame文本输入,还有很多其他模块。"这是EzText的示例代码:

# EzText example
from pygame.locals import *
import pygame, sys, eztext

def main():
    # initialize pygame
    pygame.init()
    # create the screen
    screen = pygame.display.set_mode((640,240))
    # fill the screen w/ white
    screen.fill((255,255,255))
    # here is the magic: making the text input
    # create an input with a max length of 45,
    # and a red color and a prompt saying 'type here: '
    txtbx = eztext.Input(maxlength=45, color=(255,0,0), prompt='type here: ')
    # create the pygame clock
    clock = pygame.time.Clock()
    # main loop!

    while 1:
        # make sure the program is running at 30 fps
        clock.tick(30)

        # events for txtbx
        events = pygame.event.get()
        # process other events
        for event in events:
            # close it x button si pressed
            if event.type == QUIT: return

        # clear the screen
        screen.fill((255,255,255))
        # update txtbx
        txtbx.update(events)
        # blit txtbx on the sceen
        txtbx.draw(screen)
        # refresh the display
        pygame.display.flip()

if __name__ == '__main__': main()

答案 2 :(得分:0)

我最近编写了另一个模块,可以更轻松地插入文本。您只需创建一个TextInput - 对象,然后在游戏的每一帧中为其提供事件,最后使用get_surface()检索渲染的曲面。

这是一个演示如何使用它的示例程序:

import pygame_textinput # Import the textinput-module
import pygame
pygame.init()

# Create TextInput-object
textinput = pygame_textinput.TextInput()

screen = pygame.display.set_mode((1000, 200))
clock = pygame.time.Clock()

while True:
    screen.fill((225, 225, 225))

    events = pygame.event.get()
    for event in events:
        if event.type == pygame.QUIT:
            exit()

    # Feed it with events every frame
    textinput.update(events)
    # Blit its surface onto the screen
    screen.blit(textinput.get_surface(), (10, 10))

    pygame.display.update()
    clock.tick(30)

如果您想在按下return后处理用户输入,只需等到update() - 方法返回True

if textinput.update(events):
    foo()

更详细的信息和源代码可以在[我的github页面](my github page上找到。