python为什么不接受大写或符号

时间:2013-05-07 14:57:45

标签: python python-2.7 textbox pygame

附加的代码正确接受数字或字母 使用限制(休息)但不接受 大写字母或符号+

我可能还有一些简单的事情。我有 只是刚开始使用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()

1 个答案:

答案 0 :(得分:0)

键盘事件KEYDOWNKEYUP(请参阅pygame.event模块)创建具有附加属性的pygame.event.Event对象。可以从key属性(例如K_RETURN K_a)获得按下的键,而mod属性包含带有其他修饰符的位集(例如{{1} })。 “ Unicode”属性提供键盘输入的Unicode表示形式。

如果要获取大写字母,则可以使用事件的KMOD_LSHIFTkey属性或使用mod属性来困惑输入。

在函数unicode中返回事件的keyunicode

get_key()

在字符串中添加unicode符号:

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