初学者,我正在创建一个非常简单的“登录”样式程序,目前我使用if语句来查看用户输入的内容是否与我已声明的内容相匹配,如果他们做得对,他们会得到“登录“消息,如果没有,则程序终止。
但是,我希望这样,用户在终止之前最多可以尝试3次获取凭据。我该怎么做呢?
import tkinter as tk
class NumberBox():
def __init__(self, root, display_number):
self.number_label = tk.Label(root, text=display_number)
self.number_label.pack()
def changeNumber(self, display_number):
self.number_label.config(text=display_number)
class NumberBoxesList():
def __init__(self, root, start_number = 5):
self.number = start_number
self.root = root
self.boxes = []
tk.Button(root, text="Add Class", command= self.addBox).pack()
tk.Button(root, text="Number UP", command=lambda: self.change_number("add")).pack()
tk.Button(root, text="Number DOWN", command=lambda: self.change_number("subtract")).pack()
def addBox(self):
self.boxes.append(NumberBox(self.root, self.number))
def change_number(self, operation):
if operation == "add":
self.number += 1
if operation == "subtract":
self.number -= 1
for box in self.boxes:
box.changeNumber(self.number)
root = tk.Tk()
boxList = NumberBoxesList(root)
for _ in range(5):
boxList.addBox()
root.mainloop()
非常感谢
答案 0 :(得分:1)
我也会使用这样的循环:
List<String> usernames = accessClass.setUsernames();
List<String> passwords = accessClass.setPasswords();
while(attempts > 0 && !loggedIn) {
System.out.print("Please enter your username: ");
user1 = wordScan.next();
int attempts = 3;
boolean loggedIn = false;
attempts = attempts -1;
if(usernames.contains(user1)){
System.out.print("Now enter your password: ");
pass1=wordScan.next();
if(passwords.contains(pass1)){
System.out.println("Logged in.");
System.out.println("Your username is "+user1);
loggedIn = true;
random.setSeed(System.currentTimeMillis());
numGen = random.nextInt(899999)+100000;
System.out.println("Your access code is: "+numGen);
}
}
}
if(!loggedIn) {
System.out.println("Invalid Username or password... Terminating.");
System.exit(0);
}
wordScan.close();
}
答案 1 :(得分:0)
如果你想最多循环3次,这样的事情可以解决问题:
for (int i = 0; i<3; i++)
{
... your code
// when username + password match : use break; at the end in order not to do the remaining loops
}
答案 2 :(得分:0)
for
或while
循环应该足够了,如果你的用户和密码数组是链接的(user1有pass1,user2有pass2等等),你可以获得列表中的索引使用indexOf
并比较两者:
if(usernames.contains(user1)){
System.out.print("Now enter your password: ");
for(int i = 0; i < 3; i++){
pass1 = wordScan.next();
if(passwords.contains(pass1)
&& usernames.indexOf(user1) == passwords.indexOf(pass1)){
// correct
break;
} else if (i == 2){
// incorrect and end of try
}
}
}
答案 3 :(得分:0)
试试这段代码:
INSERT ... ON CONFLICT DO NOTHING/UPDATE