我有一个登录程序,可以检查列表中的密码和用户名。如果找到凭据,则弹出一个对话框窗口,显示“成功”,否则显示“无效凭证”。
但是,我遇到的问题是,每行显示一个对话框窗口,而不是枚举列表,然后显示正确的提示。简而言之,我的程序显示每行的上述提示之一。
我正在使用PyQt4作为GUI,这是我的代码:
def process_login(self, username, password):
loggedin = False
file = open('acclist.txt')
login_info = [line.strip().split() for line in file]
while not loggedin:
for pos, line in enumerate(login_info):
if username == line[0] and password == line[1]:
QtGui.QMessageBox.information(self, 'Login', 'Login Successful')
loggedin = True
if loggedin is not True:
QtGui.QMessageBox.warning(self, 'Warning!', 'Incorrect credentials')
有什么想法吗?
答案 0 :(得分:2)
你真的不需要while
循环。凭证与break
匹配后,您可以遍历文件行,否则如果循环结束且没有匹配,则登录失败。像这样:
def process_login(self, username, password):
loggedin = False
file = open('acclist.txt')
login_info = [line.strip().split() for line in file]
file.close()
for line in login_info:
if username == line[0] and password == line[1]:
QtGui.QMessageBox.information(self, 'Login', 'Login Successful')
loggedin = True
break
if not loggedin:
QtGui.QMessageBox.warning(self, 'Warning!', 'Incorrect credentials')
答案 1 :(得分:0)
问题是你的Dialog在for循环中。意味着它正在为每个元素打开。解决这个问题的方法就像:
def process_login(self, username, password):
loggedin = False
file = open('Accounts.txt')
login_info = [line.strip().split() for line in file]
while not loggedin:
incorrect = False
for pos, line in enumerate(login_info):
if username == line[0] and password == line[1]:
loggedin = True
if loggedin is not True:
incorrect = True
if incorrect:
QtGui.QMessageBox.warning(self, 'Warning!', 'Incorrect credentials'
else:
QtGui.QMessageBox.information(self, 'Login', 'Login Successful')
答案 2 :(得分:0)
def process_login(self, username, password):
file = open('acclist.txt')
login_info = [line.strip().split() for line in file]
while True:
for pos, line in enumerate(login_info):
if username == line[0] and password == line[1]:
QtGui.QMessageBox.information(self, 'Login', 'Login Successful')
break
QtGui.QMessageBox.warning(self, 'Warning!', 'Incorrect credentials')
break
注意:while
循环并不重要,它用作登录成功/失败的上下文,而不是保存外部范围变量
不要忘记close
文件,更好的实现就是这样
def process_login(self, username, password):
logged_in = False
with open('acclist.txt', 'r') as read_file:
for line in read_file:
if username == line[0] and password == line[1]:
QtGui.QMessageBox.information(self, 'Login', 'Login Successful')
logged_in=True
break
if not logged_in:
QtGui.QMessageBox.warning(self, 'Warning!', 'Incorrect credentials')