Question

I need to create a GUI application with Tkinter that requires a lot of text-field entries. The user has to input all entries, then use a 'Run' button to execute a particular function. What I want to do is: include a functionality that restores ALL text data entered by the user from a previous session, so that the user doesn't have to enter all the data again and again each time. I could use the entry_box.set('desired string') option, but this is static and does not take into account the previous GUI sessions.

For example, in the following script:

#!usr/bin/env python
from Tkinter import *

# Define input retrieve function for application input
def retrieve_text():
    print(app_entry.get())

if __name__ == "__main__":

    # Create window (or form)
    app_win = Tk()

    # Create label
    app_label = Label(app_win, text="Enter value")
    app_label.pack()

    # Create entry box
    app_entry = Entry(app_win)
    app_entry.pack()

    # Create button
    app_button = Button(app_win, text="Print Value", command=retrieve_text)
    app_button.pack()

    # Initialize GUI loop
    app_win.mainloop()

I run this GUI and enter 'Value1' in the entry box. Then, I want to close the window, re-run it and the entry 'Value1' to appear by default. Each session should display the value from the previous session (The value is manually entered only the first time). Is there any way to do this?

This would be very useful because in my case, a user only has to change one or two fields out of around 10 each time the GUI is rerun.

Was it helpful?

Solution

In your main, add a handler to close event using this.

 app_win.protocol("WM_DELETE_WINDOW", handler)

Now, whenever the close button will be pressed, the function handler will be called.

def handler():
    f = open("backup", "w")
    f.write(app_entry.get())
    f.close()
    app_win.quit()

Now, you can modify your program to read the file & set the text when the script is restarted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top