我的逻辑/ if / else语句似乎有问题!问题在于,如果我输入错误的密码,但可以说正确的用户名,没有任何反应,类似的情况发生在学生和老师身上,我只是不确定要改变什么。谢谢。
错误:
File "/Users/Sebastian/Desktop/DQS/login.py", line 43, in _login_btn_clickked
if ( student_usernames.index(username) == student_passwords.index(password) ):
ValueError: tuple.index(x): x not in tuple
from tkinter import *
import tkinter.messagebox as tm
class LoginFrame(Frame):
def __init__(self, master):
super().__init__(master)
self.label_1 = Label(self, text="Username")
self.label_2 = Label(self, text="Password")
self.entry_1 = Entry(self)
self.entry_2 = Entry(self, show="*")
self.label_1.grid(row=0, sticky=E)
self.label_2.grid(row=1, sticky=E)
self.entry_1.grid(row=0, column=1)
self.entry_2.grid(row=1, column=1)
self.checkbox = Checkbutton(self, text="Keep me logged in")
self.checkbox.grid(columnspan=2)
self.logbtn = Button(self, text="Login", command = self._login_btn_clickked)
self.logbtn.grid(columnspan=2)
self.pack()
def _login_btn_clickked(self):
#print("Clicked")
username = self.entry_1.get()
password = self.entry_2.get()
#print(username, password)
student_usernames = ("C100", "C200", "C300")
student_passwords = ("PASS", "PASS1", "PASS2")
teacher_usernames = ("T100", "T200", "T300")
teacher_passwords = ("TPASS", "TPASS1", "TPASS3")
if username in student_usernames:
if ( student_usernames.index(username) == student_passwords.index(password) ):
tm.showinfo("Login info", "Welcome Student")
else:
tm.showerror("Login error", "Incorrect information")
elif username in teacher_usernames:
if ( teacher_usernames.index(username) == teacher_passwords.index(password) ):
tm.showinfo("Login info", "Welcome Teacher")
else:
tm.showerror("Login error", "Incorrect information")
else:
tm.showerror("Login error", "Incorrect information")
root = Tk()
lf = LoginFrame(root)
root.mainloop()
答案 0 :(得分:0)
您假设输入密码始终位于您定义为包含密码的元组之一中。你可以很容易地打破这个,简单地传入一个未包含在其中一个元组中的东西。你是条件中断,因为你在错误信息中看到它试图找到该值的索引,但它甚至不在元组中。因此,ValueError
例外。
您需要检查密码是否在相应的学生/教师密码元组以及用户名中,然后您可以检查索引。
所以,这将是if username in student_usernames and password in student_passwords:
作为一个例子。
或者,您可以通过DeMorgan的法律扭转逻辑并使用:
if not (username in student_usernames or password in student_passwords)
答案 1 :(得分:0)
student_passwords.index(password)
假设password
实际存在student_passwords
。您可以改为使用if username in student_usernames and password in student_passwords:
或使用try: except ValueError:
E.g。
if username in student_usernames and password in student_passwords:
if ( student_usernames.index(username) == student_passwords.index(password) ):
tm.showinfo("Login info", "Welcome Student")
else:
tm.showerror("Login error", "Incorrect information")
elif username in teacher_usernames and password in teacher_passwords:
if ( teacher_usernames.index(username) == teacher_passwords.index(password) ):
tm.showinfo("Login info", "Welcome Teacher")
else:
tm.showerror("Login error", "Incorrect information")
else:
tm.showerror("Login error", "Incorrect information")