Search code examples
python-3.xuser-interfacetkintersaving-data

Tkinter GUI creates another frame with its own buttons and entries, how can I save this product to be loaded at anytime?


I created a tkinter GUI, that according to the data entered in it, creates another frame with its own buttons, entries and functions.

Now, I want the user to be able to save this product as a file, and be able to open it when ever it's needed, that has the same buttons and entries that were created.

I have tried filedialog.asksaveasfilename(defaultextension=... ) but it does not work. I have been looking for a filetype for tkinter files. But maybe, because I am new to python I am not seeing the correct path to finding an answer. I will really appreciate if anyone can help me.


Solution

  • Try playing around with the below. It does what I think you need it to:

    from tkinter import *
    import json
    
    class App:
        def __init__(self, root):
            self.root = root
            self.keys = ["0", "1", "2"]
            self.widget = [(Label(self.root), Entry(self.root)), (Label(self.root), Entry(self.root)), (Label(self.root), Entry(self.root))]
            self.button = Button(self.root, text="Save", command=self.save)
            for i in self.widget:
                [1].pack()
            for i in self.widget:
                i[0].pack()
           self.button.pack()
            try:
                with open("data.json", "r") as f:
                    self.data = json.load(f)
                    f.close()
                    for i in self.keys:
                        self.widget[int(i)][0].configure(text=self.data[i])
                print(self.data)
            except FileNotFoundError:
                print("File not found")
            except KeyError:
                print("Keys do not match")
        def save(self):
            for (i, c) in self.widget:
                i.configure(text=c.get())
            with open("data.json", "w") as f:
                json.dump({self.keys[0]: self.widget[0][1].get(), self.keys[1]: self.widget[1][1].get(), self.keys[2]: self.widget[2][1].get()}, f)
                f.close()
    
    root = Tk()
    App(root)
    root.mainloop()