将变量保存在文本文件中 [英] Saving a variable in a text file

查看:31
本文介绍了将变量保存在文本文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将变量(包括其值)保存到文本文件中,以便下次打开我的程序时,任何更改都会自动保存到文本文件中.例如:

I would like to save variable (including its values) into a text file, so that the next time my program is opened, any changes will be automatically saved into the text file .For example:

    balance = total_savings - total_expenses 

我将如何将变量本身保存到文本文件中,而不仅仅是将其值保存到文本文件中?此部分为注册页面

How would I go about saving the variable itself into a text file instead of only its value? This section is for the register page

    from tkinter import *
    register = Tk()
    Label(register, text ="Username").grid(row = 0)
    Label(register, text ="Password").grid(row = 1)

    e1 = Entry (register)
    e2 = Entry (register, show= "*")

    e1.grid(row = 0, column = 1)
    e2.grid(row = 1, column = 1)

    username = e1.get()
    password = e2.get()


    button1 = Button(register, text = "Register", command = register.quit)
    button1.grid(columnspan = 2)
    button1.bind("<Button-1>")

    import json as serializer
    with open('godhelpme.txt', 'w') as f:
        serializer.dump(username, f)
    with open('some_file.txt', 'w') as f:
        serializer.dump(password, f)


    register.mainloop()

更改代码:

    from tkinter import *
    register = Tk()
    Label(register, text ="Username").grid(row = 0)
    Label(register, text ="Password").grid(row = 1)

    username = StringVar()
    password = StringVar()

    e1 = Entry (register, textvariable=username)
    e2 = Entry (register, textvariable=password, show= "*")

    e1.grid(row = 0, column = 1)
    e2.grid(row = 1, column = 1)


    button1 = Button(register, text = "Register", command = register.quit)
    button1.grid(columnspan = 2)
    button1.bind("<Button-1>")

    import json as serializer
    with open('godhelpme.txt', 'w') as f:
        serializer.dump(username.get(), f)
    with open('some_file.txt', 'w') as f:
        serializer.dump(password.get(), f)

登录代码:

    from tkinter import *
    login = Tk()
    Label(login, text ="Username").grid(row = 0)
    Label(login, text ="Password").grid(row = 1)

    username = StringVar()
    password = StringVar()

    i1 = Entry(login, textvariable=username)
    i2 = Entry(login, textvariable=password, show = "*")

    i1.grid(row = 0, column = 1)
    i2.grid(row = 1, column = 1)

    def clickLogin():
            import json as serializer
            f = open('godhelpme.txt', 'r')
            file = open('some_file.txt', 'r')
            if username == serializer.load(f):
                    print ("hi")
            else:
                    print ("invalid username")
                    if password == serializer.load(file):
                            print ("HELLOOOO")
                    else:
                            print ("invalid password")



    button2 = Button(login, text = "Log In", command = clickLogin)
    button2.grid(columnspan = 2)


    login.mainloop()

推荐答案

您必须在编译时知道变量的名称.所以你需要做的就是:

You have to know the variable's name at compilation time. So all you need to do is:

with open('some_file.txt', 'w') as f:
    f.write("balance %d" % balance)

这可以更方便地使用 dict 用于将名称映射到值的对象.

This can be more convenient to manage using a dict object for mapping names to values.

您可能还想了解 picklejson 模块,它们提供了简单的序列化对象,例如 dict.

You may also want to read about the pickle or json modules which provide easy serialization of objects such as dict.

使用pickle等序列化程序的方式a> 是:

The way to use a serializer such as pickle is:

import pickle as serializer

balance = total_savings - total_expenses 
with open('some_file.txt', 'w') as f:
    serializer.dump( balance, f)

您可以在提供的代码中将 pickle 更改为 json 以使用其他标准序列化程序并以 json 格式存储对象.

You can change pickle to json in the provided code to use the other standard serializer and store objects in json format.

在您的示例中,您尝试存储来自 tkinterEntry 小部件的文本.在此处阅读相关信息.

In your example you're trying to store text from tkinter's Entry widget. Read about it here.

您可能错过的是使用 StringVariable 来捕获输入的文本:

What you probably miss is using a StringVariable to capture the entered text:

为变量创建StringVar:

username = StringVar()
password = StringVar()

将 StringVar 变量注册到 Entry 小部件:

Register StringVar variables to Entry widgets:

e1 = Entry (register, textvariable=username)
e2 = Entry (register, textvariable=password, show= "*")

使用 StringVar 将内容保存在两个单独的文件中:

Save content using StringVar in two seperate files:

import json as serializer
with open('godhelpme.txt', 'w') as f:
    serializer.dump(username.get(), f)
with open('some_file.txt', 'w') as f:
    serializer.dump(password.get(), f)

如果你想让它们在同一个文件中创建一个映射(dict)并存储它:

If you want them in the same file create a mapping (dict) and store it:

import json as serializer
with open('godhelpme.txt', 'w') as f:
    serializer.dump(
        {
            "username": username.get(),
            "password": password.get()
        }, f
    )

编辑 2:

您在输入文本之前使用了序列化.将 save 功能(可以稍后退出)注册到注册按钮.这样它就会在用户点击它之后被调用(这意味着内容已经存在).方法如下:

Edit 2:

You were using the serialization before entering text. Register a save function (that can later exit) to the register button. This way it will be called after the user clicked it (that means the content is already there). Here is how:

from tkinter import *

def save():
    import json as serializer
    with open('godhelpme.txt', 'w') as f:
        serializer.dump(username.get(), f)
    with open('some_file.txt', 'w') as f:
        serializer.dump(password.get(), f)
    register.quit()

register = Tk()
Label(register, text ="Username").grid(row = 0)
Label(register, text ="Password").grid(row = 1)

username = StringVar()
password = StringVar()

e1 = Entry (register, textvariable=username)
e2 = Entry (register, textvariable=password, show= "*")

e1.grid(row = 0, column = 1)
e2.grid(row = 1, column = 1)

# changed "command"
button1 = Button(register, text = "Register", command = save)
button1.grid(columnspan = 2)
button1.bind("<Button-1>")
register.mainloop()

之前发生的是保存到文件过程在用户插入任何数据之前立即发生.通过向按钮 click 注册一个函数,可以确保只有当按钮被按下时,函数才会执行.

What happened before was the save-to-file process happened immediately before the user inserts any data. By registering a function to the button click you can ensure that only when the button is pressed, the function executes.

强烈建议您在调试环境中使用旧代码或使用一些打印件来弄清楚代码的工作原理.

I strongly suggest you play with your old code in a debug environment or use some prints to figure out how the code works.

这篇关于将变量保存在文本文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆