定义的代码在使用tkinter按钮调用之前执行

我正在开发一个程序,该程序允许用户存储其用户名和密码,并对存储它们的纯文本进行哈希处理(因此注释掉了哈希码)。但是,我将tkinter用于GUI,我的一个按钮在被调用之前会运行一个已定义的函数。 (请忽略所有看似随机的评论)


import basehash
import tkinter
import tkinter as tk
import os
from tkinter import*
from tkinter import messagebox
from string import ascii_lowercase

userPaths = ['./usernames2.txt', './username.txt', './usernames3.txt']
passPaths = ['./Passwords2.txt', './Passwords.txt', './Passwords3.txt']
#create new doc and assign doc array
# use an array for password of paths where the password is stored on a plaintext file
password = ("test") 
usernameguess1 = ("")
passwordguess1 = ("")
loggedin = 0
activeUser = ""
activeUserNum = 0
hashbase = basehash.base52()

LETTERS = {letter: str(index) for index, letter in enumerate(ascii_lowercase, start=1)} 

def alphabet_position(text):
    text = text.lower()

    numbers = [LETTERS[character] for character in text if character in LETTERS]

    return ''.join(numbers)

def loginpage():

    #Gui Formatting
    root = tkinter.Toplevel()
    root.resizable(width=FALSE, height=FALSE)
    root.title("HasherTest_V0.1 Login")
    root.geometry("300x150")

    #Username and password boxes
    usernametext = tkinter.Label(root, text="Username:")
    usernameguess = tkinter.Entry(root)
    passwordtext = tkinter.Label(root, text="Password:")
    passwordguess = tkinter.Entry(root, show="*")

    usernameguess1 = usernameguess
    def trylogin():
        print ("Logging In...")


        for x in range(0,len(userPaths)):
            #get path data here
            file1 = open(userPaths[x], "r")
            original = file1.read()
            file1.close()
            if original == usernameguess.get():
                userPaths[x] = activeUser
                x = activeUserNum


        file1 = open(passPaths[activeUserNum], "r")
        original = file1.read()
        original = hashbase.unhash(original)
        file1.close()

        if usernameguess.get() == activeUser and alphabet_position(passwordguess.get()) == original:
           print ("Success!")
           messagebox.showinfo("Success ", "Successfully logged in.")
           viewbutton = tkinter.Button(root, text="Veiw Saved Passwords", command=lambda:[root.withdraw()])
           viewbutton.pack()

        else:
            print ("Error: (Incorrect value entered)")
            messagebox.showinfo("Error", "Sorry, but your username or password is incorrect. Try again")
        #login button


    def viewtest():
        if loggedin == 1:
            messagebox.showinfo("Success ", "Loading Passwords")


        else:
            messagebox.showinfo("Error", "You need to sign in first!")



    #login button
    root.deiconify() #shows login window
    attemptlogin = tkinter.Button(root, text="Login", command=trylogin)
    attemptview = tkinter.Button(root, text="View Stored Passwords", command=viewtest)


    usernametext.pack()
    usernameguess.pack()
    passwordtext.pack()
    passwordguess.pack()
    attemptlogin.pack()
    attemptview.pack()
    window.mainloop()

def signuppage():
    root2 = tkinter.Toplevel()
    root2.resizable(width=FALSE, height=FALSE)
    root2.title("HasherTest_V0.1 Login")
    root2.geometry("300x150")
    #Gui Formatting (again)
    root2 = tkinter.Tk()
    root2.resizable(width=FALSE, height=FALSE)
    root2.title("HasherTest_V0.1")
    root2.geometry("300x150")
    #Username and password boxes
    masterusername = tkinter.Label(root2, text="Enter Master Username:")
    masterusernamebox = tkinter.Entry(root2)
    masterpassword = tkinter.Label(root2, text="Enter Master Password:")
    masterpasswordbox = tkinter.Entry(root2, show="*")


    def trysignup(): 

        newuser = str(masterusernamebox.get())

        length = len(userPaths)

        namepath = './usernames3.txt'
        userPaths[length-1] = namepath
        newfile = open(namepath, 'w')
        newfile.write(newuser)
        newfile.close()

        password = str(masterpasswordbox.get())
        numPass = alphabet_position(password)
        print(numPass)

        """hashbase = basehash.base52()
        #not taking numPass as an int
        #run test 328-i
        hashval = hashbase.hash(numPass)
        print(hashval)

        unhashed = hashbase.unhash(hashval)
        print(unhashed)"""

        path = './passwords3.txt'
        newfile = open(path, 'w')
        newfile.write(numPass)
        newfile.close()

        if newuser == "":
            messagebox.showinfo("Error code 0", "No input entered")
        else:
            return 


    #login button
    mastersignupbutton = tkinter.Button(root2, text="Sign Up 1", command=trysignup())
    mastersignupbutton.pack()



    masterusername.pack()
    masterusernamebox.pack()
    masterpassword.pack()
    masterpasswordbox.pack()
    window.mainloop()


window = tkinter.Tk()
window.resizable(width=FALSE, height=FALSE)
window.title("HasherTest_V0.1")
window.geometry("300x150")

loginbutton = tkinter.Button(window, text="Login", command=lambda:[window.withdraw(), loginpage()])
signupbutton = tkinter.Button(window, text="Sign Up", command=lambda:[window.withdraw(), signuppage()])

loginbutton.pack()
signupbutton.pack()

window.mainloop()

如果运行此代码,然后按注册按钮,然后输入主用户名和密码,则应将它们都写入记事本文件,并且如果框中没有任何内容,则显示错误消息。但是,这些功能都不起作用。当用户按下主窗口上的第一个“注册”按钮时,它将(以某种方式)运行错误代码,并在出现错误代码之前给出错误代码。当在“输入主用户名和密码”窗口上单击“注册1”按钮时,错误代码应显示是否没有任何内容。我不知道为什么代码会提早运行。能否请您回答原因,甚至是固定代码?谢谢,Tf0R24。

评论
  • punde
    punde 回复

    改成

    mastersignupbutton = tkinter.Button(root2, text="Sign Up 1", command=trysignup)
    
  • 行文华
    行文华 回复

    创建按钮时,常见的错误是在函数名称后包含括号。代替这个:

    mastersignupbutton = tkinter.Button(root2, text="Sign Up 1", command=trysignup())
    

    做这个:

    mastersignupbutton = tkinter.Button(root2, text="Sign Up 1", command=trysignup)
    

    which is exactly the same but without the parentheses after command=trysingup. If you want to call a function that requires arguments, do this:

    tkinter.Button(master, text="text", command=lambda: function_that_requires_arguments(x, y))