user13112566
user13112566

Reputation:

Saving and Loading the GUI of a complex tkinter application

I have a very complex tkinter application, it's an editor, for now it's not so much different than window's notepad but it will have tons of functions that it doesn't. The problem is that i didn't correctly understand the way used to save the gui in this topic:

Save and Load GUI-tkinter - Stack Overflow

For example why save_state(self) isn't defined in Example(tk.Frame) and why even the class is a frame? Mine is a Tk() widget can that method work with it? Also doesn't functions need to be called how they are working without calling? and could you tell wha are doing "previous":, "expression":, "result":in this part? :

def save_state(self):
        try:
            data = {
                "previous": self.previous_values,
                "expression": self.expressionVar.get(),
                "result": self.resultLabel.cget("text"),
            }
            with open(FILENAME, "wb") as f:
                pickle.dump(data, f)

        except Exception as e:
            print
            "error saving state:", str(e)

Here is my code:

My editor

Upvotes: 0

Views: 526

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385800

You shouldn't worry about the code in the example, and instead focus on the concept. You need to write two functions: one to save the data and one to restore the data.

The function to save the data must gather then data into some sort of data structure. The code you linked to chose a simple dictionary of values that is pickled. You could use a sqlite database, a yaml file, a dictionary, a custom object, whatever you want.

The function to restore the data must read the data in at startup, and then put the data back into the appropriate widgets.

For a text editor, you're probably going to want to save the names of the open files. So, your "save" function can simply write the list of filenames to a file. Your "reload" function needs to read the list of filenames, and for each file it can open up a tab in your editor.

The only other thing you need to do is arrange for the "save" function to be called on exit. If you have a function to exit the program you can add it there. In the code you linked to, it arranged for the function to be called automatically when the program exits by doing root.wm_protocol("WM_DELETE_WINDOW", self.save_state).

Upvotes: 1

Related Questions