Nuno
Nuno

Reputation: 45

Open and Save as Json configurations files of the user settings in an app made with tkinter

When the json file is saved it works, but when the same file is open, won't load the user settings in to the app.


def save_as():
    data = {
        'win left': left_w.get(),
        'win top': top_w.get(),
        'win width': width_w.get(),
        'win height': height_w.get()
    }
    with open('{}'.format(filedialog.asksaveasfilename(initialdir="/", 
              title="Select file", filetypes=(("json files", 
              "*.json"), ("all files", "*.*")))), 'w', encoding='utf-8') as f:

        json.dump(data, f, ensure_ascii=False, indent=2)
        f.close()
        print(data)


def open_file():
    open_config = filedialog.askopenfilename(initialdir="/", title="Select 
                  file", filetypes=(("json files", "*.json"), 
                  ("all files", "*.*")))

    config = open(open_config)
    json_file = json.load(config)
    config.close()
    print(json_file)

# Menu
filemenu.add_command(label="Open", command=open_file)
filemenu.add_command(label="Save as...", command=save_as)

# Entry fields
left_w = IntVar()
top_w = IntVar()
width_w = IntVar()
height_w = IntVar()
wl = Entry(master=page2, textvariable=left_w, width=6).grid(column=1, row=1)
wt = Entry(master=page2, textvariable=top_w, width=6).grid(column=3, row=1)
ww = Entry(master=page2, textvariable=width_w, width=6).grid(column=5, row=1)
wh = Entry(master=page2, textvariable=height_w, width=6).grid(column=7, row=1)

I want to be enable to save and load the user settings of the entry fields on the App. Right now only save, when the file is loaded, the App print the user settings of the file but don't load the user settings, and don't give any error.

Upvotes: 0

Views: 147

Answers (1)

Nuno
Nuno

Reputation: 45

On the def open_file() I just add:

left_w.set(data['win left'])
top_w.set(data['win top'])

Now when the json file is load, the app replace the values for the ones that are on the file.

Upvotes: 1

Related Questions