2016-01-29 34 views
0

我目前正在制作一个Python 3的程序,其中我需要用户输入程序稍后会使用的密码。我现在面临的问题是,如果我只使用password = input("Enter password: "),用户输入的字符将在屏幕上可见 - 我宁愿用asterixes替换它们。在Python 3上输入一个隐藏的字符串

当然,我可以使用pygame的和做的是这样的:

import pygame, sys 
pygame.init() 
def text (string, screen, color, position, size, flag=''): 
    font = pygame.font.Font(None, size) 
    text = font.render(string, 1, (color[0], color[1], color[2])) 
    textpos = text.get_rect(centerx=position[0], centery=position[1]) 
    screen.blit(text, textpos) 
    pygame.display.flip() 
screen = pygame.display.set_mode((640, 480)) 
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890' 
text('Enter password:', screen, [255, 0, 0], [320, 100], 36) 
pygame.display.flip() 
password = '' 
password_trigger = True 
while password_trigger: 
    for event in pygame.event.get(): 
     if event.type == pygame.QUIT: 
      sys.exit() 
     elif event.type == pygame.KEYDOWN: 
      if chr(int(str(event.key))) in alphabet: 
       password += chr(int(str(event.key))) 
       screen.fill((0, 0, 0)) 
       text('*'*len(password), screen, [0, 50, 250], [320, 360], 36) 
       text('Enter password:', screen, [255, 0, 0], [320, 100], 36) 
       pygame.display.flip() 
      elif (event.key == pygame.K_RETURN) and (len(password) > 0): 
       password_trigger = False 

但似乎有点矫枉过正(也Pygame的显示器将在一个新的窗口,我的东西,我宁愿避免打开) 。有没有一个简单的方法来做到这一点?

+0

因为我在家里的房间工作,没有陌生人,我真的很讨厌密码屏蔽。它使我无尽的悲伤。我不是唯一一个觉得这样的人。即使在工作场所,这也不是真正的安全问题,部分是安全剧场的一种形式。我建议你让它可选。 –

回答

8

您可以让用户输入使用标准getpass模块完全隐藏:

>>> import getpass 
>>> pw = getpass.getpass("Enter password: ") 
Enter password: 
>>> pw 
'myPassword' 
+0

好的,但我可以用星号替换密码而不是完全隐藏密码吗? –

+0

文档中提到“提示用户输入密码而不回显”,所以它看起来并不如此,但库源包含在Python中,因此您应该可以使用它来了解如何创建修改后的版本显示星号。 (请参阅http://svn.python.org/projects/python/trunk/Lib/getpass.py) – bgporter

相关问题