Pygame как сделать окно ввода

Обновлено: 05.05.2024

Pygame Text Input Module

  • TextInputVisualizer which can be used to both manage and draw text input. Simply pass all events returned by pygame.event.get() to it every frame, and blit its surface attribute on the screen.
  • TextInputManager that can be used to just manage inputted text, with no visual aspect. Used by TextInputVisualizer behind the scenes.

Simplest way is using pypi:

All arguments to the constructor are optional. Once constructed, call update every frame with all pygame events as an argument, then blit it's surface field to the screen, like so:

All arguments are optional.

Argument Description
manager The TextInputManager used to manage the input
font_object The pygame.font.Font object used for rendering
antialias whether to render the font antialiased or not
font_color color of font rendered
cursor_blink_interval The interval of the cursor blinking, in ms
cursor_width The width of the cursor, in pixels
cursor_color The color of the cursor

All arguments above are also fields that can be accessed and modified on the fly, e.g. like this:

Field Description
value (string) The text entered so far
surface The pygame.Surface object with entered text & cursor on it and a transparent background. Cannot be set.
cursor_visible (bool) wether the cursor is currently visible or not. Flips every cursor_interval ms as long as update is called continuously.
Method Description
update(events) Call this method every frame for as long as input should be processed and cursor_visible should be updated.

Notes on the newer version:

  • You have to watch for "return" presses by the user yourself, e.g. like this:
  • Contrary to the old version, key-stroke repeats are not manually introduced anymore, since they can now be enabled within pygame directly:

This new version has also been optimized such that you can modify any fields on the fly and the actual surface will only re-render if you access it using textinput.surface - and only if you actually modified any values.

If you prefer to draw the text on the screen yourself, you can use TextInputManager to only manage the string that has been typed so far.

Like TextInputVisualizer , you feed its update method all events received by pygame.event.get() which you want it to process. TextInputVisualizer does this for you inside its update method if you pass it a TextInputManager .

Argument Description
initial The initial value (text)
validator A function taking a string and returning a bool . Every time an input modifies the value, this function is called with the modified value as an argument; if the function returns True , the input is accepted, otherwise the input is ignored.

So say you want to only allow input to up to 5 letters, you could do that with

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.

5 Answers 5

You can define a rect as the area of the input box. If a pygame.MOUSEBUTTONDOWN event occurs, use the colliderect method of the input_box rect to check if it collides with the event.pos and then activate it by setting a active variable to True .

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

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

There are also third party modules available like pygame_textinput.

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 rect and a rect_color parameter to the *_init_() function and adding

to the update(self, events) function.

Use the KEYDOWN event to get the input from the keyboard (see pygame.event ). The key that was pressed can be obtained from the key attribute of the pygame.event.Event object. unicode contains a single character string that is the fully translated character. Add the character to the text when a key is pressed.
Two special keys need to be dealt with. If RETURN is pressed, the input is finished. If BACKSPACE is pressed, the last character of the input text must be removed:

Use the algorithm in a pygame.sprite.Sprite class. Handle the event in the update method.Determine whether the mouse clicks in the text entry field with collidepoint (see How to detect when a rectangular object, image or sprite is clicked) and activate the text input box:

Pass the list of events to the update method of the Group that contains the Sprite:


Minimal example: repl.it/@Rabbid76/PyGame-SpriteTextInput

Я хочу получить некоторый ввод текста от пользователя в Python и отобразить то, что они вводят, в текстовом поле, и когда они нажимают ввод, он сохраняется в строке.

Я везде искал, но ничего не нашел. Я использую Pygame.

4 ответа

Вы можете определить прямоугольник как область поля ввода. Если происходит событие pygame.MOUSEBUTTONDOWN , используйте метод colliderect прямоугольника input_box , чтобы проверить, не сталкивается ли оно с event.pos , а затем активируйте его, установив active переменная в True .

Если поле активно, вы можете ввести что-нибудь, и Pygame сгенерирует события pygame.KEYDOWN с атрибутом unicode , который вы можете просто добавить в строку, например text += event.unicode . Если пользователь нажимает клавишу ВВОД, вы можете сделать что-нибудь со строкой text (в этом примере я просто распечатал ее) и сбросить ее на '' .

Вот объектно-ориентированный вариант, который позволяет легко создавать несколько полей ввода:

Также доступны сторонние модули, такие как pygame_textinput.

Вы можете найти отличный модуль для ввода текста Pygame здесь.

Пользуюсь им уже какое-то время и мне это очень нравится. Учебное пособие по его использованию включено в описание.

Однако я добавил возможность рисовать (цветной) прямоугольник вокруг текста, добавив параметр rect и rect_color к * _ init _ () и добавление

К функции update (self, events) .

Модуль pygame_gui позволяет создавать поле ввода text_input от пользователя с помощью создание экземпляра UITextEntryLine . Вам нужно будет настроить экземпляр, как описано в кратком руководстве по началу работы .

Получите текст, если нажать Enter:

Используйте событие KEYDOWN для ввода с клавиатуры (см. >). Нажатую клавишу можно получить из атрибута key в объект pygame.event.Event . unicode содержит односимвольную строку, которая является полностью переведенным символом. Добавьте символ в текст при нажатии клавиши.
Необходимо разобраться с двумя специальными ключами. Если нажать RETURN , ввод завершен. Если нажать BACKSPACE , последний символ вводимого текста должен быть удален:

Используйте алгоритм в pygame.sprite.Sprite класс. Обработайте событие в методе update . Определите, щелкает ли мышь в поле ввода текста с помощью collidepoint (см. Как определить щелчок по прямоугольному объекту, изображению или спрайту) и активировать поле ввода текста:

Передайте список событий методу update Group , которая содержит Sprite :

Начнем с создания пустого окна Pygame. Ниже приведена базовая структура игры, написанной с использованием Pygame:

(2) . .screen = pygame.display.set_mode((1200, 800))

(4) . . . .for event in pygame.event.get():

(5) . . . . . .if event.type == pygame.QUIT:

Программа начинается с импортирования модуля sys и pygame. Модуль pygame содержит функциональность, необходимую для создания игры, а модуль sys ­завершает игру по команде игрока.

Игра Alien Invasion начинается с определения функции run_game(). Строка pygame.init() (1) инициализирует настройки, необходимые Pygame для нормальной работы. В точке (2) вызов pygame.display.set_mode() создает отображаемую область screen, на которой прорисовываются все графические элементы игры. Аргумент (1200, 800) представляет собой кортеж, определяющий размеры игрового окна. Передавая эти размеры pygame.display.set_mode(), мы создаем игровое окно с шириной 1200 пикселов и высотой 800 пикселов. (Вы можете изменить эти значения в соответствии с размерами своего монитора.)

Объект screen называется поверхностью (surface). Поверхность в Pygame представляет часть экрана, на которой отображается игровой элемент. Каждый элемент в игре (например, пришелец или корабль игрока) представлен поверхностью. Поверхность, возвращаемая display.set_mode(), представляет все игровое окно. При активизации игрового цикла анимации эта поверхность автоматически перерисовывается при каждом проходе цикла.

Процессом игры управляет цикл while (3), который содержит цикл событий и код, управляющий обновлениями экрана. Событием называется действие, выполняемое пользователем во время игры (например, нажатие клавиши или перемещение мыши). Чтобы наша программа реагировала на события, мы напишем цикл событий для прослушивания событий и выполнения соответствующей операции в зависимости от типа произошедшего события. Этим циклом событий является цикл for в точке (4).

Чтобы получить доступ к событиям, обнаруженным Pygame, мы используем метод pygame.event.get(). При любом событии клавиатуры или мыши отрабатывает цикл for. В этом цикле мы пишем серию команд if для обнаружения и обработки конкретных событий. Например, когда игрок щелкает на кнопке закрытия игрового окна, программа обнаруживает событие pygame.QUIT, и программа вызывает метод sys.exit() для выхода из игры (5).

Вызов pygame.display.flip() ? приказывает Pygame отобразить последний отрисованный экран. В данном случае при каждом выполнении цикла while будет отображаться пустой экран со стиранием старого экрана, так что виден будет только новый экран. При перемещении игровых элементов вызов pygame.display.flip() будет постоянно обновлять экран, отображая игровые элементы в новых позициях и скрывая старые изображения; таким образом создается иллюзия плавного движения.

Последняя строка в этой базовой структуре вызывает метод run_game(), который инициализирует игру и запускает основной цикл.

In pygame, text cannot be written directly to the screen. The first step is to create a Font object with a given font size. The second step is to render the text into an image with a given color. The third step is to blit the image to the screen. These are the steps:

Once the font is created, its size cannot be changed. A Font object is used to create a Surface object from a string. Pygame does not provide a direct way to write text onto a Surface object. The method render() must be used to create a Surface object from the text, which then can be blit to the screen. The method render() can only render single lines. A newline character is not rendered.

Initialize a font¶

Initializing the font can take a few seconds. On a MacBook Air the the creation of a system Font object:

took more then 8 seconds:

The function get_fonts() returns a list of all installed fonts. The following code checks what fonts are on your system and how many, and prints them to the console:

You will get something like this:

Render the text¶

The font object can render a given text into an image. In the example below, we place a blue bounding rectangle around that text image:

We then create two more fonts, Chalkduster and Didot at a size of 72 points. We render a text with both fonts:

Finally the text images are blit to the screen like regular images:

This is the result:

../_images/text1.jpg

Here is the full code.

Edit text with the keybord¶

The keyboard event can be used to edit a text. First we create a text which we save in a string variable text and which we render to an image:

Then we define the bounding rectangle and furthermore a cursor rectangle which is juxtaposed to the text bounding rectangle:

Inside the event loop we watch out for KEYDOWN events. If the key press is a BACKSPACE and the lenght of the string is larger than 0, then we remove the last character, else we append the new character to the text variable:

Then we render the modified text, update the bounding rectangle, and place the cursor box at the end of the updated bounding rectangle:

Add a blinking cursor¶

In order to make the cursor more visible, we let it blink every 0.5 seconds. We do this using the time.time() floating point value:

Читайте также: