我是一名A级计算机学生,我是班上唯一一个可以使用Python编写代码的人。甚至我的老师也没有学过这门语言。我正在尝试编写一个登录程序,当正确放入信息时退出该登录程序并显示欢迎屏幕图像(我尚未对该部分进行编码)。在3次登录尝试失败后,它必须关闭并显示失败消息。尝试更改我的尝试变量以使elif语句在多次登录失败后工作以及根据相关的if / elif语句使tkinter窗口终止/关闭时,我遇到了许多逻辑错误。这是行之有效的,我在这个网站上看了很多代码示例,找不到任何东西,我可以帮忙修一下我的代码吗?
代码:
from tkinter import * #Importing graphics
attempts = 0 #Defining attempts variable
def OperatingProgram(): #Defining active program
class Application(Frame):
global attempts
def __init__(self,master):
super(Application, self).__init__(master) #Set __init__ to the master class
self.grid()
self.InnerWindow() #Creates function
def InnerWindow(self): #Defining the buttons and input boxes within the window
global attempts
print("Booted log in screen")
self.title = Label(self, text=" Please log in, you have " + str(attempts) + " incorrect attempts.") #Title
self.title.grid(row=0, column=2)
self.user_entry_label = Label(self, text="Username: ") #Username box
self.user_entry_label.grid(row=1, column=1)
self.user_entry = Entry(self) #Username entry box
self.user_entry.grid(row=1, column=2)
self.pass_entry_label = Label(self, text="Password: ") #Password label
self.pass_entry_label.grid(row=2, column=1)
self.pass_entry = Entry(self) #Password entry box
self.pass_entry.grid(row=2, column=2)
self.sign_in_butt = Button(self, text="Log In",command = self.logging_in) #Log in button
self.sign_in_butt.grid(row=5, column=2)
def logging_in(self):
global attempts
print("processing")
user_get = self.user_entry.get() #Retrieve Username
pass_get = self.pass_entry.get() #Retrieve Password
if user_get == 'octo' and pass_get == 'burger': #Statement for successful info
import time
time.sleep(2) #Delays for 2 seconds
print("Welcome!")
QuitProgram()
elif user_get != 'octo' or pass_get != 'burger': #Statement for any failed info
if attempts >= 2: #Statement if user has gained 3 failed attempts
import time
time.sleep(2)
print("Sorry, you have given incorrect details too many times!")
print("This program will now end itself")
QuitProgram()
else: #Statement if user still has enough attempts remaining
import time
time.sleep(2)
print("Incorrect username, please try again")
attempts += 1
else: #Statement only exists to complete this if statement block
print("I don't know what you did but it is very wrong.")
root = Tk() #Window format
root.title("Log in screen")
root.geometry("320x100")
app = Application(root) #The frame is inside the widget
root.mainloop() #Keeps the window open/running
def QuitProgram(): #Defining program termination
import sys
sys.exit()
OperatingProgram()
答案 0 :(得分:1)
请考虑logging_in方法中的以下两行:
if user_get == 'octo' and pass_get == 'burger':
elif user_get != 'octo' or pass_get != 'burger':
因此,如果登录凭据正确,则执行第一次测试后的代码。如果它们不正确,则执行第二次测试后的代码。
但是,您希望在多次失败后执行的代码属于第三个测试子句:
elif attempts >= 3:
问题是,执行的线程永远不会看到这个测试,因为第一个或第二个已经评估为true(登录凭据是正确的,登录凭据是不正确的) - 它们可能需要它们两者都要在检查尝试值之前评估为假。
解决此问题的最简单方法是更改
elif attempts >= 3:
行阅读
if attempts >= 3:
如果您觉得有必要,可以调整else子句/添加一个新子句。