nearoo / pygame-text-input Goto Github PK
View Code? Open in Web Editor NEWa small module that enables you to input text with your keyboard using pygame
License: MIT License
a small module that enables you to input text with your keyboard using pygame
License: MIT License
In your sample code, if i keep typing the letters will appear out of the screen.
i want to make boundaries so the text wont go out of the screen. Is there a way to do this?
If I have a Snake Game
On Startup can appear this pygame-text-input as 2nd window get username and after close it... and continue playing the snake game... ?
I was just wondering whether you could post some example code for changing the font used. I'm having some problems (but I'm probably just putting it in wrong). This is what I've got:
menuTxt = pygame_textinput.TextInput(text_color = WHITE, font_family = 'Fonts/PrintChar21.ttf', font_size = 60)
Hey Nearoo,
Thanks for creating that package. However, I am encountering with some problem. When I try to write in the text input box, the marks of cursor is being left on the screen. Also, when I try to delete it, It is being deleted but not being updated. I am leaving gif below, did you ever encounter with that problem before?
Thanks.
Hi, I was hoping to use pygame-text-input for a program I am developing for an A-Level project, but there is no licensing info which I could find. Github projects with no license are All Rights Reserved by default, so it would be illegal for me to use the file without explicit permission. Is it possible to add a license to the library to clear up when and how it can be used?
I used the library and it was all fine until I wanted to convert my game into an .exe with Pyinstaller.
This is the error message:
Type error: Expected str, bytes or os.PathLike object, not BytesIO File "pygame_textinput\pygametextinput.py", line 139 in "__init__"
Probably something with the fonts...
Maybe someone can help me. Thank you! (:
Where do I put module?
until adding "from pygame_textinput import *"
Happy to do a pull request, but I'm new-ish to python/pygame/git, so I might be missing something
People might be coming to pygame relatively new to python so it would be good to have examples fully working without any changes.
On that note, it would be nice to have a bare-bones example of actually using input after hitting enter. A parse(text) method that just prints "Parsing: <textinput.value>" and then resets textinput.value to an empty string
Hi, i have some issues when I press CTRL + , a squarre appear next to letter...
Using the same script as in #41 , if I switch to the other textbox, the cursor becomes a vertical bar (not flashing) in the previous textbox. The vertical bar is only present in used textboxes and not in untouched textboxes. In the screenshot I first placed the cursor in between 2 and 3 and then switched to the other textbox.
A "size" parameter, or similar. The maximum amount of characters that can be typed into the input field.
A "allowed" parameter, or similar. A string, containing allowed characters for input.
I'm trying to have the user type something in around y=100, but I can't figure out how to shift it down. From what I understand the actual text is being rendered to a pygame surface, but I don't know how that connects to the pygame display. Have you experiment with this?
Hello,
I am having an issue with initializing maximum string lenght. I am getting error mentioned in the title. My code is:
cur_amount = pygame_textinput.TextInput( initial_string="1", font_family="pixel_font.ttf", font_size=20, text_color=FONT_COLOR, cursor_color=FONT_COLOR, max_string_lenght=3, )
All of the other arguments work great, just having problem with this one. What could be the issue?
Thank you!
This is a very useful module, but down in README, the table of TextInput arguments doesn't include initial string as the first argument, one has to read the module to figure that one out. Prehaps it would be better to mention, that the 1st parameter of TextInput constructor is not the path to font, but the initial string.
Cheers, Nezumi
A project that I'm building uses this code for it's text boxes (thanks in advance for publishing this, it really helped me out), and I came across an... unintended effect. Put simply, my code listens for the True return value (from the update function) while the text box is active, and bypasses the update command when it does. Unfortunately, this allows the K_Return event to be stored in the keyrepeat_counters dict, and the corresponding KEYUP event is never sent to remove it. So anytime I update that text box a K_Return event is raised, which in turn disables the text box on the next tick. A simple fix would be to filter out that key when adding to keyrepeat_counters, but I'll let you call that shot.
Hey This module is great and very useful
However, Ive been looking through the source and I cant really figure out a way to clear text that been entered?
I understand its self.curson - something but not sure how to implement this
Could someone help me out please.
Thanks for the great module guys and for the help
Regards
Naeem
Hi, I am attempting to write out a column of numbers to the text box. At the moment, the column will print horizontally. \n is not recognized. Is there a way to create new lines programmatically in the text box input_string or is this not possible with current state of the code?
Unfortunately, i cant use more than one text input at once. There are two instances but they share the content...
See code:
import pygame_textinput
import pygame
pygame.init()
# Create TextInput-object
textinput = pygame_textinput.TextInputVisualizer()
textinput2 = pygame_textinput.TextInputVisualizer()
screen = pygame.display.set_mode((1000, 200))
clock = pygame.time.Clock()
switch = False
while True:
screen.fill((225, 225, 225))
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
exit()
if [ev for ev in events if ev.type == pygame.KEYDOWN and ev.key == pygame.K_RETURN]:
switch = not switch
# Feed it with events every frame
if switch:
textinput.update(events)
else:
textinput2.update(events)
# Blit its surface onto the screen
screen.blit(textinput.surface, (10, 10))
screen.blit(textinput2.surface, (10, 30))
pygame.display.update()
clock.tick(30)
i just change:
if not os.path.isfile(font_family): font_family = pygame.font.Font("华文宋体.ttf", 40)
self.font_object = pygame.font.Font("华文宋体.ttf", 40)
and add this at the beginning
# -- coding: utf-8 --
it can show chinese, but when you type in, the word just go on and on and on.........can't stop.
can you fix that?
a lot of thanks!
Hello I'm having some issue using this module (fantastic work btw) in Pyinstaller, every time I enter a section with the Text Input utilised the program crashes, I have tried taking all of the functions from the main file into my program which worked within the regular IDLE however once again encountered the same problem when compiled with Pyinstaller. I say that there was some mention of Pyinstalled within one of the files provided however I'm unsure as to what that means. Hope to hear back soon.
When you try to write a accent mark and press space bar that letter start to repeat without any way to stop it.
This text input window should be converted into a basic text editor where we can type in multiple lines automatically either on completion of a text input line length or pressing the key even before.
Also, having a mouse clicking functionality can allow the user to place the mouse cursor anywhere in the multi-line document for editing.
The Unicode characters by using the modifier keys should also be resolved as they can not be rendered properly. But options like Ctrl + C
and Ctrl + V
should give the basic clipboard copy-paste functionality.
How do you install it? Maybe add something about it in the README.md
In my program when someone types a letter i.e. Q, two Qs will appear. Do you have any idea why this might be?
https://github.com/rocket-pig/pygame-base-template
Thanks for your great module :)
Is there a way in which the memory of currently stored text can be cleared, if I say start on menu page one, open menu page 2, press enter to save the entered text to a variable, then go back to menu page 1: Can a command then be run which clears the text so that when I go to menu page 2 again there isn't last time's text still in the box? There is no documentation explaining if this is or is not the case. Thanks
Hey, so I've used your text input a lot for my pygame projects (it's really an amazing module that should be a part of standard pygame). One issue I've recently run into is I've been making a GUI for my sudoku game, and as such made 81 different instances of text input and placed them in their boxes. The problem I've had is that each box seems to be a replicate of the others, even tho they are all instantiated separately. In this sense, each box has a blinking cursor, and changing one box is replicated in all the others. Is there a way I could change the source code so that the text input surface must be clicked so only that specific text input is changed? Attached you'll find a short clip of the problem.
Cheers!
How will I be able to install this module on windows? I'm sorry if this is a dumb question.
When switching between instances of the same Surface, both instances containing a text Field,
textField = textinput.get.surface()
Any text entered from the previous Instance remains on-screen and is not cleared when a new instance of
textinput.get_surface()
is blitted to the Surface.
Hi
Thanks for making this module I really appreciate it, I'm currently struggling with getting it displaying anything right now.
I've tried using the code you have a more complex example from the github as well writing a basic one.
The variables exist for TextInputVisualizer() but don't seem to display.
The text_input.value variable is empty within the loop and doesn't show any keystrokes apart from certain special characters such as ';' and '1' but no others? This still doesn't display them on screen though.
Any help would be appreciated.
This is the code right now:
`
def run(self):
while True:
text_input = TextInputVisualizer()
events = pygame.event.get()
text_input.update(events)
self.screen.blit(text_input.surface, (50, 50))
print(text_input.value)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# print(event)
if event.type == pygame.KEYDOWN:
self.key_pressed = event.key
# if self.in_dialog:
self.screen.fill('black')
self.in_dialog = self.level.run(self.key_pressed)
pygame.display.update()
self.clock.tick(FPS)
`
self.screen is defined as:
`
self.screen = pygame.display.set_mode((WIDTH, HEIGTH))
`
Thanks
Arthur
Resizing the font through font_size attribute isn't working for me. I used the sample code and then put textinput.font_size = 10, but nothing happened to the font
This error occurs when opening a .exe file from pyinstaller:
Traceback (most recent call last):
File "main.py", line 189, in
File "pygame_textinput\pygame_textinput.py", line 139, in init
TypeError: expected str, bytes or os.PathLike object, not BytesIO
How can I fix it?
and the code is showen as below
import pygame
import numpy as np
from enum import Enum
import sys
import pygame_textinput
from main import game
SIZE = (700, 500)
WIDTH = SIZE[0]
HEIGHT = SIZE[1]
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLOCKSIZE = 20
BLOCKWIDTH = 28
BLOCKHEIGHT = 16
GAMEWIDTH = (BLOCKWIDTH - 1) * BLOCKSIZE
GAMEHEIGHT = (BLOCKHEIGHT - 1) * BLOCKSIZE
INFO_LUX = GAMEWIDTH
INFO_LUY = 0
INFO_NUM = 0
WARNING_LUX = 0
WARNING_LUY = GAMEHEIGHT + 3
CARD_LUX = 10
CARD_LUY = GAMEHEIGHT + 40
CHOICE_LUX = GAMEWIDTH + 3
CHOICE_LUY = GAMEHEIGHT + 3
# def
CARD_CHOOSING = 0
text_input = pygame_textinput.TextInputVisualizer()
text_input.value = 'tesing'
text_input.font_color = WHITE
pygame.font.init()
font = pygame.font.SysFont('microsoft Yahei', 16)
class MODE(Enum):
INFO = 1
WARNING = 2
CHOICE = 3
NONE = 4
CENTER = 5
def draw_rect(screen ,x, y, w, h, color):
rect = pygame.Rect(x, y, w, h)
pygame.draw.rect(screen, color, rect, 0)
def draw_point(screen, x, y, color):
rect = pygame.Rect(20 * x + 1, 20 * y + 1, BLOCKSIZE - 1 , BLOCKSIZE - 1)
pygame.draw.rect(screen, color, rect, 0)
def card_check(a):
if a == ' ':
return False
elif a != '(' and a != ')':
# print(a)
return True
def get_card(card='( E )(END)( D )'):
end_list = []
return_list = []
for i in card:
tmp = card_check(i)
if tmp is not None:
end_list.append(tmp)
tt = []
for index, tmp in enumerate(end_list):
tt.append(tmp)
if index % 3 == 2:
return_list.append(tt)
tt = []
return return_list
def draw_grid(screen, grid):
for x, heng in enumerate(grid):
for y, point in enumerate(heng):
if point:
color = RED
else:
color = BLACK
draw_point(screen, x, y, color)
def draw_card(screen, index, card):
"""
:param screen:
:param index: 第几张卡
:param card:
:return:
"""
color_list = get_card(card)
x = index * (BLOCKSIZE * 3 + 10) + CARD_LUX
y = CARD_LUY
card_center_x = int(x + BLOCKSIZE * 1.5)
card_center_y = int(y + BLOCKSIZE * 3) + 20
print_message(screen, card_center_x, card_center_y, str(index), WHITE, mode=MODE.CENTER)
for xx, lis in enumerate(color_list):
for yy, color in enumerate(lis):
if color:
color = RED
else:
color = WHITE
print(color)
draw_rect(screen, x + xx * BLOCKSIZE, y + yy * BLOCKSIZE, BLOCKSIZE-1, BLOCKSIZE-1, color)
def print_message(screen, x, y, message, color, mode:MODE):
text = font.render(message, False, color)
text_rect = text.get_rect()
w = text_rect.w // 2
h = text_rect.h // 2
if mode != MODE.CENTER:
if mode == MODE.INFO:
global INFO_NUM
y += INFO_NUM * text_rect.h
INFO_NUM += 1
text_rect.center = (x + w + 3, y + h)
screen.blit(text, text_rect)
else:
text_rect.center = (x, y)
screen.blit(text, text_rect)
def print_INFO(screen, message, color):
x = INFO_LUX + 10
y = INFO_LUY
print_message(screen, x, y, message, color, MODE.INFO)
def print_WARNING(screen, message, color):
x = WARNING_LUX
y = WARNING_LUY
print_message(screen, x, y, message, color, MODE.WARNING)
def print_CHOICE(screen, message, color):
x = CHOICE_LUX
y = CHOICE_LUY
print_message(screen, x, y, message, color, MODE.CHOICE)
# def from_gird_to_map(grid, screen):
# a = np.load('./a.npy')
# block_size = 20
# x, y = 0, 0
# for x in range(a.shape[0]):
# for y in range(a.shape[1]):
# rect = pygame.Rect(x, y, block_size, block_size)
# pygame.draw.rect(screen, WHITE if )
# y += block_size
# x += block_size
# def choose_card(screen, event):
# index = CARD_CHOOSING
# print_message(screen, inde)
def show_player(screen):
print_INFO(screen, '-+-Players-+-', WHITE)
for index, player in enumerate(game.players):
print_INFO(screen, str(player), WHITE)
def get_27_15(a:np.array):
tmp = []
for i in range(9):
x = i * 5 + 2
tmp += [x - 1, x, x + 1]
# print(tmp)
a = a.T
a = a[tmp]
return a
def gaming():
a = np.load('./a.npy')
a = get_27_15(a)
pygame.init()
screen = pygame.display.set_mode(SIZE)
pygame.display.set_caption('Sab')
RIGHT = False
done = False
clock = pygame.time.Clock()
# screen.blit(text_input.surface, (CHOICE_LUX, CHOICE_LUY + 50))
while not done:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
exit()
text_input.update(events)
# game
# draw
global INFO_NUM
INFO_NUM = 0
draw_grid(screen, a)
print_WARNING(screen, 'Jesus ', WHITE)
print_CHOICE(screen, 'choice', WHITE)
draw_card(screen, 0, '( | )(-+-)( )')
draw_card(screen, 1, '( | )( +-)( )')
draw_card(screen, 2, '( | )(-+ )( )')
draw_card(screen, 3, '( | )(-+-)( | )')
# INFO
show_player(screen)
for x in range(BLOCKWIDTH):
pygame.draw.line(screen, WHITE, (x * BLOCKSIZE, 0), (x * BLOCKSIZE, GAMEHEIGHT), 1)
for y in range(BLOCKHEIGHT):
pygame.draw.line(screen, WHITE, (0, y * BLOCKSIZE), (GAMEWIDTH, y * BLOCKSIZE), 1 )
# pygame.display.flip()
pygame.draw.line(screen, GREEN, (GAMEWIDTH, 0), (GAMEWIDTH, HEIGHT), 3)
pygame.draw.line(screen, GREEN, (0, GAMEHEIGHT), (WIDTH, GAMEHEIGHT ), 3)
pygame.display.update()
screen.blit(text_input.surface, (CHOICE_LUX, CHOICE_LUY + 50))
clock.tick(60)
pygame.quit()
if __name__ == '__main__':
gaming()
# get_card()
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.