Python Tkinter,我可以限制参赛人数吗?

时间:2018-08-08 13:20:06

标签: python-3.x tkinter

如何限制用户输入的数量,以便如果用户已经尝试了5次错误,系统将立即结束?

我尝试照常使用While循环来实现。但是,while循环似乎无法计算错误输入的数量。

请让我知道该怎么办。赞赏

import tkinter as tk
import csv
from tkinter import messagebox


def user_login():
    locals()
    entry_user_name = entry_usr_name.get()
    entry_user_pwd = entry_usr_pwd.get()

    with open(r'user.csv', 'r') as user_file
         reader = csv.reader(user_file)
         user = list(reader)
    found = False
    count1 = 5
    for count in range(len(user)):
         if entry_user_name == user[count][0]:
              if entry_user_pwd == user[count][1]:
                 target = count
                 found = True
                 break
              else: found = False
         else: found = False
               count1 -= 1
    if not found:
              tk.messagebox.showerror(title='Error',
                                      message='Invalid password. Please enter again. You have '+str(count1)+ ' left')
    if count1 == 0:
              tk.messagebox.showerror(title='Error',
                                line1='Too many input. The system will be ended immediately',
                                line2='This will be recorded in the security system')
    if found:
         tk.messagebox.showinfo(title='Successful login',
                                message='Valid password.')
    startpage()



window = tk.Tk()
entry_username = tk.Entry(window, font='Courier 17')
entry_pwd = tk.Entry(window,font='Courier 17')
entry_usr_name.place(x=330, y=245)
entry_usr_pwd.place(x=330, y=345)

login_button= tk.Button(window,
                        command=user_login) # with some setting
login_button.place(x=440, y=420)
window.mainloop()

1 个答案:

答案 0 :(得分:1)

您可以使用跟踪变量来记录一个人进行了多少次尝试。

这是一个简单的例子。

import tkinter as tk


root = tk.Tk()

counter = 1 # tracking variable

tk.Label(root, text="User Name: ").grid(row=0, column=0)
tk.Label(root, text="Password: ").grid(row=1, column=0)
entry_name = tk.Entry(root)
entry_pass = tk.Entry(root)
entry_name.grid(row=0, column=1)
entry_pass.grid(row=1, column=1)


def check_login():
    global counter, entry_name, entry_pass
    x = entry_name.get()
    y = entry_pass.get()
    if counter <= 5: # if counter 5 or less then check login info
        if x == "Bob" and y == "mypassword":
            print("Correct!")
        else:
            counter += 1 # add 1 to counter
            print("Bad login! Please try again")
    else:
        print("Exceeded max attempt.")

tk.Button(root, text="Login", command=check_login).grid(row=2, column=0, columnspan=2)
root.mainloop()