You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python出现Unexpected indent错误但无对应缩进的问题排查

Hey there, let's fix that unexpected indent error (and a few other bugs you'll hit right after) in your code:

1. The root cause of the unexpected indent error

Your sign_up() function has an unclosed try statement—there's no corresponding except or finally block to wrap up the try logic. Python interprets the following def log_in() line as part of the try block, which causes an indentation conflict (you can't define a function inside a try block like this without proper nesting, which isn't what you intended).

Fix for sign_up():

Add an except block to handle potential file IO errors, or remove the try if you don't need error handling (though adding error handling is better for user feedback):

def sign_up():
    adduser = e3.get()
    addpassword = e4.get()
    try:
        hashed_password = hash_password(addpassword)
        with open(filename, "w") as f_obj:
            json.dump(adduser, f_obj)
        with open(filename2, "w") as f:
            json.dump(hashed_password, f)
        messagebox.showinfo("Info", "You have successfully signed up!")
    except IOError as e:
        messagebox.showerror("Error", f"Failed to save your account: {str(e)}")

2. Logic and indentation issues in log_in()

Your log_in() function has a broken flow: if the user file doesn't exist (triggering FileNotFoundError), you immediately try to open the same file again, which will just throw the same error. Plus, the indentation here was likely messed up because of the earlier sign_up() problem.

Fix for log_in():

Restructure the logic to first check if the user exists, then validate the password:

def log_in():
    usernameguess = e1.get()
    passwordguess = e2.get()
    try:
        # Read saved username
        with open(filename) as f_obj:
            saved_username = json.load(f_obj)
        # Read saved hashed password
        with open(filename2) as f:
            saved_hashed_pwd = json.load(f)
        
        if saved_username == usernameguess:
            if check_password(saved_hashed_pwd, passwordguess):
                messagebox.showinfo("Success", "You're logged into your account!")
            else:
                messagebox.showerror("Error", "Incorrect password")
        else:
            messagebox.showerror("Error", "Incorrect username")
    except FileNotFoundError:
        messagebox.showerror("Error", "No account found! Please sign up first.")

3. Bonus: Fixing single-user limitation

Right now, your code only supports one user (since w mode overwrites the file each time someone signs up). If you want to support multiple users, use a single JSON file to store a dictionary of usernames and their hashed passwords:

# Replace your two filename variables with one
user_data_file = "user_data.json"

# Updated sign_up for multiple users
def sign_up():
    adduser = e3.get()
    addpassword = e4.get()
    if not adduser or not addpassword:
        messagebox.showerror("Error", "Username and password can't be empty!")
        return
    try:
        hashed_password = hash_password(addpassword)
        # Load existing users (or create empty dict if file doesn't exist)
        try:
            with open(user_data_file, "r") as f:
                users = json.load(f)
        except FileNotFoundError:
            users = {}
        if adduser in users:
            messagebox.showerror("Error", "Username already taken!")
            return
        users[adduser] = hashed_password
        with open(user_data_file, "w") as f:
            json.dump(users, f)
        messagebox.showinfo("Info", "You have successfully signed up!")
    except IOError as e:
        messagebox.showerror("Error", f"Failed to save your account: {str(e)}")

# Updated log_in for multiple users
def log_in():
    usernameguess = e1.get()
    passwordguess = e2.get()
    if not usernameguess or not passwordguess:
        messagebox.showerror("Error", "Please enter both username and password!")
        return
    try:
        with open(user_data_file, "r") as f:
            users = json.load(f)
        if usernameguess not in users:
            messagebox.showerror("Error", "Username not found! Please sign up first.")
            return
        if check_password(users[usernameguess], passwordguess):
            messagebox.showinfo("Success", "You're logged into your account!")
        else:
            messagebox.showerror("Error", "Incorrect password")
    except FileNotFoundError:
        messagebox.showerror("Error", "No accounts found! Please sign up first.")

Once you fix the unclosed try block in sign_up(), the indent error should disappear immediately. The other fixes will make your app more robust and user-friendly.

内容的提问来源于stack exchange,提问作者B. Sommer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:09:51