附加的代码使用限制(rest)正确接受数字或字母,但它不会接受大写或符号,如+
可能有一些简单的事情我没有做过。我才刚刚开始使用 Python——我的其余代码似乎可以正常工作
'''
Text input
restrict to certain inputs
letters or numbers (rest)
'''
# will not accept upper case or '+'
import pygame, pygame.font, pygame.event, pygame.draw, string
import sys
from pygame.locals import *
#Screen size
x_Size=600
y_Size=600
#Restrict
rest1='1234567890-+.'
rest2='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
rest3 = rest1 + rest2 # accept all
def get_key():
while 1:
event = pygame.event.poll()
if event.type == KEYDOWN:
return event.key
else:
pass
def display_box(screen, message, x, y, rest):
"Print a message in a box on the screen"
fontobject = pygame.font.Font(None,28) # font size
pygame.draw.rect(screen, (255,0,0),(x, y, 250,30), 1) # red box outline
if len(message) != 0:
screen.blit(fontobject.render(message, 1, (255,0,0)),
(x, y)) # red text
pygame.display.flip()
def clear_box(screen, x, y):
pygame.draw.rect(screen,(255,255,255),(x, y, 300, 90), 0)
pygame.display.flip()
def ask(screen, question, x, y, rest):
#ask(screen, question, position x,y, restriction) answer
pygame.font.init()
current_string = []
display_box(screen, (question + ": " + string.join(current_string,"")), x, y, rest)
while 1:
inkey = get_key()
print inkey
if inkey == K_BACKSPACE:
current_string = current_string[0:-1]
#print current_string
elif inkey == K_RETURN:
break
elif inkey >= 127:
pass
elif chr(inkey) in rest:
z = chr(inkey)
print 'z',z
current_string.append(chr(inkey))
clear_box(screen,x,y)
display_box(screen, (question + ": " + string.join(current_string,"")), x, y, rest)
print string.join(current_string)
return string.join(current_string)
def main():
screen = pygame.display.set_mode((x_Size, y_Size))
screen.fill((255,255,255))
h=ask(screen,'Numbers', 40, 50, rest1)
k=ask(screen,'Letters',40, 70, rest2)
print h,'Numbers'
print k,'Letters'
#=======================
pygame.quit()
sys.exit()
if __name__ == '__main__': main()