Python 如何使用pygame创建文本输入框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46390231/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:36:01  来源:igfitidea点击:

How to create a text input box with pygame?

pythontextpygametextinput

提问by Deps

I want to get some text input from the user in python and display what they are typing in a text box, and when they press enter, it gets stored in a string. I've looked everywhere but i just can't find anything.(I'm using pygame)

我想在 python 中从用户那里获得一些文本输入并显示他们在文本框中输入的内容,当他们按下 Enter 键时,它被存储在一个字符串中。我到处找,但找不到任何东西。(我正在使用 pygame)

回答by skrx

You can define a rectas the area of the input box. If a pygame.MOUSEBUTTONDOWNevent occurs, use the colliderectmethod of the input_boxrect to check if it collides with the event.posand then activate it by setting a activevariable to True.

您可以定义一个矩形作为输入框的区域。如果有pygame.MOUSEBUTTONDOWN事件发生,使用rect的colliderect方法input_box来检查它是否与 发生碰撞,event.pos然后通过设置一个active变量来激活它True

If the box is active you can type something and pygame will generate pygame.KEYDOWNevents which have a unicodeattribute that you can simply add to a string, e.g. text += event.unicode. If the user presses enter, you can do something with the textstring (in the example I just print it) and reset it to ''.

如果该框处于活动状态,您可以输入一些内容,pygame 将生成pygame.KEYDOWN具有unicode您可以简单地添加到字符串的属性的事件,例如text += event.unicode. 如果用户按 Enter,您可以对text字符串执行某些操作(在示例中我只是打印它)并将其重置为''.

import pygame as pg


def main():
    screen = pg.display.set_mode((640, 480))
    font = pg.font.Font(None, 32)
    clock = pg.time.Clock()
    input_box = pg.Rect(100, 100, 140, 32)
    color_inactive = pg.Color('lightskyblue3')
    color_active = pg.Color('dodgerblue2')
    color = color_inactive
    active = False
    text = ''
    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            if event.type == pg.MOUSEBUTTONDOWN:
                # If the user clicked on the input_box rect.
                if input_box.collidepoint(event.pos):
                    # Toggle the active variable.
                    active = not active
                else:
                    active = False
                # Change the current color of the input box.
                color = color_active if active else color_inactive
            if event.type == pg.KEYDOWN:
                if active:
                    if event.key == pg.K_RETURN:
                        print(text)
                        text = ''
                    elif event.key == pg.K_BACKSPACE:
                        text = text[:-1]
                    else:
                        text += event.unicode

        screen.fill((30, 30, 30))
        # Render the current text.
        txt_surface = font.render(text, True, color)
        # Resize the box if the text is too long.
        width = max(200, txt_surface.get_width()+10)
        input_box.w = width
        # Blit the text.
        screen.blit(txt_surface, (input_box.x+5, input_box.y+5))
        # Blit the input_box rect.
        pg.draw.rect(screen, color, input_box, 2)

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    pg.init()
    main()
    pg.quit()


Here's an object-oriented variant that allows you to easily create multiple input boxes:

这是一个面向对象的变体,可让您轻松创建多个输入框:

import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
COLOR_INACTIVE = pg.Color('lightskyblue3')
COLOR_ACTIVE = pg.Color('dodgerblue2')
FONT = pg.font.Font(None, 32)


class InputBox:

    def __init__(self, x, y, w, h, text=''):
        self.rect = pg.Rect(x, y, w, h)
        self.color = COLOR_INACTIVE
        self.text = text
        self.txt_surface = FONT.render(text, True, self.color)
        self.active = False

    def handle_event(self, event):
        if event.type == pg.MOUSEBUTTONDOWN:
            # If the user clicked on the input_box rect.
            if self.rect.collidepoint(event.pos):
                # Toggle the active variable.
                self.active = not self.active
            else:
                self.active = False
            # Change the current color of the input box.
            self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE
        if event.type == pg.KEYDOWN:
            if self.active:
                if event.key == pg.K_RETURN:
                    print(self.text)
                    self.text = ''
                elif event.key == pg.K_BACKSPACE:
                    self.text = self.text[:-1]
                else:
                    self.text += event.unicode
                # Re-render the text.
                self.txt_surface = FONT.render(self.text, True, self.color)

    def update(self):
        # Resize the box if the text is too long.
        width = max(200, self.txt_surface.get_width()+10)
        self.rect.w = width

    def draw(self, screen):
        # Blit the text.
        screen.blit(self.txt_surface, (self.rect.x+5, self.rect.y+5))
        # Blit the rect.
        pg.draw.rect(screen, self.color, self.rect, 2)



def main():
    clock = pg.time.Clock()
    input_box1 = InputBox(100, 100, 140, 32)
    input_box2 = InputBox(100, 300, 140, 32)
    input_boxes = [input_box1, input_box2]
    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            for box in input_boxes:
                box.handle_event(event)

        for box in input_boxes:
            box.update()

        screen.fill((30, 30, 30))
        for box in input_boxes:
            box.draw(screen)

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    main()
    pg.quit()


There are also third party modules available like pygame_textinput.

还有第三方模块可用,如pygame_textinput

回答by Jonas De Schouwer

You can find a great module for pygame text input here .
I have been using it for a while and I really like it. A tutorial how to use it is included in the description.


However, I have added the possibility to draw a (coloured) rectangle around the text, by adding a rectand a rect_colorparameter to the __init__()function and adding

你可以在这里找到一个很棒的 pygame 文本输入模块。
我已经使用它一段时间了,我真的很喜欢它。说明中包含如何使用它的教程。


但是,我添加了在文本周围绘制(彩色)矩形的可能性,方法是向__init__()函数添加一个rect和一个rect_color参数并添加

if self.rect != None:
    pygame.draw.rect(screen, self.rect_color, self.rect)    #screen is my pygame display surface

to the update(self, events)function.

update(self, events )函数。