首页 > 解决方案 > 尝试将全局变量添加到列表而不是它们的分配

问题描述

该代码是更大程序的一部分。Save 函数保存全局数据(我知道你不应该使用全局变量)并且 Load 函数应该加载它并将全局变量更改为加载的对象。我知道列表只保存分配的对象而不是变量本身,但我不知道如何以不同的方式做到这一点。对于这种情况,有一个解决方案必须改变我保存变量的方式我还将工作保存函数放入代码中。谢谢您的帮助。

我在互联网上搜索了一个解决方案并尝试了一些模块,但无法得到任何工作。


#works
def Save():
    global a, b, c, d, e
    toSave = [a, b, c, d, e]
    count = 0
    f = open("file.txt", "w") #file where the vars get saved and should be loaded from
    for x in range(len(toSave)):
        save = toSave[count]
        f.write(str(save)+"\n") #writes the objects the vars are assigned to into a file which each objekt having it's own row
        count += 1
    tkinter.messagebox.showinfo("Save","Your progress got saved.")

def Load():
    global a, b, c, d, e
    toLoad = [a, b, c, d, e]
    count = 0
    f = open("file.txt", "r")
    for x in range(len(toLoad)):
        toLoad[count] = f.readline() #changes the numbers in the list. Should change the global vars
        count += 1
    tkinter.messagebox.showinfo("Load","Your progress got loaded.")

我只是想让全局变量成为保存的对象,这样我就可以在我的程序中加载和保存保存文件(这是一个小游戏)。

标签: python-3.x

解决方案


将其全部保存为 JSON 数据,并将其作为字典带回,使用它来加载全局变量。

import json
#works
def Save():
    global a, b, c, d, e
    save_dict = {
        'a': a,
        'b': b,
        'c': c,
        'd': d,
        'e': e
    }
    json_save_data = json.dumps(save_dict)
    with open('file.json' mode='w') as file:
        file.write(json_save_data)
    tkinter.messagebox.showinfo("Save","Your progress got saved.")

def Load():
    global a, b, c, d, e
    with open('file.json', "r") as file:
        data = file.readlines()
    global_dict = json.loads(data)
    a = global_dict['a']
    b = global_dict['b']
    c = global_dict['c']
    d = global_dict['d']
    e = global_dict['e']
    tkinter.messagebox.showinfo("Load","Your progress got loaded."

推荐阅读