简体   繁体   中英

Python - Need help on tkinter gui

So I am making a login gui using Tkinter and I have ran into a road-block. For some reason when I login to an account it will say Username not found (an error I put in) then it will say that it has logged in. I inputted the correct username and password but it will always say unknown username right before it says that it has logged in.

Here is my code:

from tkinter import *
import hashlib
import json

userdata_file = 'UserData.json'



class Login(Tk):
    def __init__(self):
        # Inherit from Tk parent class
        super(Login, self).__init__()

        # Setting up child class attributes
        self.geometry("750x500")
        self.title("Login Page")
        self.resizable(height = False, width = False)
        # self.iconbitmap(path to icon.ico) < setup an icon for the GUI
        self.pepper = "[]#'[]''332#4'32'4#324'"
        self.salt = "']2[3][2#3['2]['3]['#']["
        self.hasher = lambda text: hashlib.sha256((self.pepper, text, self.salt).encode()).hexdigest()
        self.usernm = StringVar()
        self.passwd = StringVar()

        # Main interface
        C = Canvas(self, height = 250, width = 300)
        filename = PhotoImage(file = "wallpaper.png")
        background_label = Label(self, image = filename)
        background_label.place(x = 0, y = 0, relwidth = 1, relheight = 1)
        C.pack()



        login_button = PhotoImage(file = "login_button.png")
        signup_button = PhotoImage(file = "signup_button.png")
        Entry(textvariable = self.usernm, font=("Arial", 15), bg="#454545", border=0).place(x = 200, y = 195, height = 40, width = 330)
        Entry(textvariable = self.passwd, font=("Arial", 15), bg="#454545", show='•', border=0).place(x = 200, y = 278, height = 40, width = 330)
        B1 = Button(command = self.login, image=login_button, bg="black", border=0, activebackground="black").place(x = 186, y = 353, height = 52, width = 146)
        login_error = Label(text="Login error", font=("Arial", 12), fg="black", border=0, bg='black').place(x = 290, y = 330, height = 21, width = 146)
        B2 = Button(command = self.signup, image=signup_button, bg="black", border=0, activebackground="black").place(x = 351, y = 353, height = 52, width = 146)
        self.login_error = login_error
        self.mainloop()


**# The main problem appears in the following methods.**


    def login(self):
        # Creates a variable of what the user entered
        self.username = self.usernm.get()
        self.password = self.passwd.get()
        with open(userdata_file) as data:
            userdata = json.load(data)
            for profile in userdata:
                if self.username == profile['Username']:
                    if self.password == profile['Password']:
                        print(f'Successfully logged into {self.username}\'s account.')
                    else:
                        print("Incorrect password.")
                else:
                    print('Username not found.')



    def signup_page(self):
        pass  # Signup page goes here

    def signup(self):  # Delete this function once signup page is made and let me know -Sticky
        self.username = self.usernm.get()
        self.password = self.passwd.get()
        can_create = False
        with open(userdata_file) as data:
            userdata = json.load(data)
            for profile in userdata:
                if self.username == profile['Username']:
                    print('Username Taken')
                if not self.username == profile['Username']:
                    print('User created')






if __name__ == "__main__":
    # Starts if the program is not imported
    login = Login()

If you know anything at all that can help me in any way please let me know because I have been stuck for the past 2 days.

The are a few issues with your code like how self.login_error is None . The solution and explanation can be found here .

For your log in function you loop over all of the people that have signed up and check if it matches that person's log in details (btw you forgot to hash the password before checking). The problem is that each time you don't find a person with that username+password it prints out "Username not found." and goes to the next person details.

Change that function to this:

def login(self):
    # Creates a variable of what the user entered
    username = self.usernm.get()
    password = self.passwd.get()
    password = self.hasher(password) # Hash the password
    found = False # Add a flag to check if the username matches
    with open(userdata_file) as data:
        userdata = json.load(data)
    # Close the file before looping
    for profile in userdata:
        if self.username == profile['Username']:
            found = True
            if self.password == profile['Password']:
                print(f'Successfully logged into {self.username}\'s account.')
                break # Stop the for loop
            else:
                print("Incorrect password.")
                break # Stop the for loop
    if not found: # If the username hasn't been found in the file
        print('Username not found.')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM