1

I am trying to write a condition, under which a value in specified dictionary changes. However, every time I load the file its back to the original value. I would like to save the new value to the dictionary, so when the file is loaded again the new value would show.Any help is appreciated.

I've tried using a different python file for dictionary, but ended up with same results. I gave pickle module a try too. No success. Any help is appreciated.

from tkinter import *

dict = {'Andrew': [67, 78, 98], 'William': [56, 90, 42], 'Anna':     [90, 88, 75]}


andrew_var = DoubleVar()
change_first_grade = Entry(root, textvariable=var)
change_first_grade.pack()

andrew_var.set(0)

if andrew_var.get() != 0:
    dict['Andrew'][0] = andrew_var.get()

How can I make that when the value in dictionary changes, it is saved, so next time opening file would have had the new value in dictionary.

GreakFreak
  • 51
  • 7
  • You mean changes program script? Why do not save dict in a file as https://stackoverflow.com/questions/19201290/how-to-save-a-dictionary-to-a-file/32216025 – Masoud Jul 10 '19 at 10:05
  • you could save it as JSON. But you have to save it every time you change value in dict and load from file at start. It will not do it automatically. The same is when you use pickle or any other file format. – furas Jul 13 '19 at 15:33

1 Answers1

1

You can keep dictionary in pickle or JSON file but before you save it you have to get value from Entry and put in dictionary. It will not do it automatically.

But you can't get value directly after you create Entry because it is not input() and it will not wait for data. Function mainloop() starts window and everthing before mainloop() is execute before you see window.

You may use Button to run function which will save it after you put value in Entry.

import tkinter as tk
import json

def load():
    global data

    try:
        with open('data.json') as f:
            data = json.load(f)
    except Exception as ex:
        print(ex)

def save(event=None):
    # update dictionary before save
    data['Andrew'][0] = int(entry.get())

    with open('data.json', 'w') as f:
        json.dump(data, f)

# ---

data = {
    'Andrew':  [67, 78, 98],
    'William': [56, 90, 42],
    'Anna':    [90, 88, 75]
}

# load at start
load()

root = tk.Tk()

entry = tk.Entry(root)
entry.pack()
entry.insert('end', data['Andrew'][0])

button = tk.Button(root, text='Save', command=save)
button.pack()

root.mainloop()

Instead Button you could bind() key Enter to function save so it would update data in file.

root = tk.Tk()

entry = tk.Entry(root)
entry.pack()
entry.insert('end', data['Andrew'][0])

entry.bind('<Return>', save)

root.mainloop()
furas
  • 134,197
  • 12
  • 106
  • 148