1

附加的代码使用限制(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()
4

1 回答 1

0

键盘事件KEYDOWNKEYUP(参见pygame.event模块)创建一个pygame.event.Event具有附加属性的对象。按下的键可以从key属性(例如K_RETURN , K_a)中获得,并且该mod属性包含一个带有附加修饰符的位集(例如KMOD_LSHIFT)。“Unicode”属性提供键盘输入的 Unicode 表示。

如果你想得到大写字母,你可以用事件的keymod属性来混淆输入,或者只使用unicode属性。

在函数中返回事件的key和:unicodeget_key()

def get_key():
  while 1:
    event = pygame.event.poll()
    if event.type == KEYDOWN:
      return event.key, event.unicode
    else:
      pass

将 unicode 符号添加到字符串中:

while 1:
    inkey, inunicode = get_key()

    if inkey == K_BACKSPACE:
        # [...]

    elif inunicode  in rest:
        current_string.append(inunicode)
于 2020-12-17T06:56:55.163 回答