我目前正在尝试学习 tkinter,因此构建一个应用程序来保存 3 个变量,在本例中为用户名、密码和网站到文本文件中。显然,实际上使用这种方法来保存密码是一个糟糕的主意,但这只是为了学习。
我遇到一个问题,我的应用程序仅在第一次运行时才能完美运行。单击按钮后,它接收 3 个变量并将它们存储在文本文件中。问题是当我再次尝试执行此操作时,出现属性错误。我希望能够附加该文件,这样我就可以填写任意数量的条目,而不必关闭它并再次打开它。
属性错误:“str”对象没有属性“get”
这是我的代码。
from tkinter import *
import tkinter.messagebox
def save_info():
global username
global password
global website
username = username.get()
password = password.get()
website = website.get()
print(username,password,website)
file = open("Software.txt","a")
file.write("Username: " + username)
file.write("\n")
file.write("Password: " + password)
file.write("\n")
file.write("Website: " + website)
file.write("\n")
file.write("----------")
file.write("\n")
file.close()
app = Tk()
app.geometry("500x500")
app.title("Password Manager")
heading = Label(text="Password Manager",fg="white",bg="blue",width="500",height="3",font="10")
heading.pack()
username_text = Label(text="Username: ")
password_text = Label(text="Password: ")
website_text = Label(text="Website: ")
username_text.place(x=15,y=70)
password_text.place(x=15,y=140)
website_text.place(x=15,y=210)
username = StringVar()
password = StringVar()
website = StringVar()
username_entry = Entry(textvariable=username,width="30")
password_entry = Entry(textvariable=password,width="30")
website_entry = Entry(textvariable=website,width="30")
username_entry.place(x=15,y=100)
password_entry.place(x=15,y=170)
website_entry.place(x=15,y=240)
button = Button(app,text="Submit Data",command=lambda:
[save_info(),onClick()],width="30",height="2",bg="lightgrey")
button.place(x=15,y=290)
def onClick():
tkinter.messagebox.showinfo("Password Manager","Data Saved Successfully")
mainloop()
最佳答案
在您的 save_info()
中,您覆盖了迄今为止 StringVar()
的 3 个变量。您必须为它们找到新的变量名称来存储字符串。
def save_info():
global username
global password
global website
username_str = username.get()
password_str = password.get()
website_str = website.get()
print(username,password,website)
file = open("Software.txt","a")
file.write("Username: " + username_str)
file.write("\n")
file.write("Password: " + password_str)
file.write("\n")
file.write("Website: " + website_str)
file.write("\n")
file.write("----------")
file.write("\n")
file.close()
关于Python Tkinter 程序无法正确将数据发送到我的文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70895736/