Search code examples
pythontkinterlogictkinter-text

Is there a way to make a textbox save by itself?


So let's say I wanted to make a code editor and I want the contents in a text box to save by itself.

How would I do that, and where would I start?

Here is my thought: I would create a function that saves the content and run it in a forever loop. But it won't work, so how would I do it.


Solution

  • Step one: make a function that saves the data:

    def save():
        data = the_text_widget.get("1.0", "end-1c")
        with open("the_filename.txt", "w") as f:
            f.write(data)
    

    Next, write a function that calls this function over some interval, like every 10 seconds:

    def autosave():
        save()
        the_text_widget.after(10000, autosave)
    

    And finally, call this function once and it will run every 10 seconds:

    autosave()
    

    This isn't the only way, but it's arguably the simplest.