Auto-save function implementation with Python and

2019-06-11 02:14发布

问题:

This might be a general question. I'm modifying a Python code wrote by former colleague. The main purpose of the code is

  1. Read some file from local
  2. Pop out a GUI to do some modification
  3. Save the file to local

The GUI is wrote with Python and Tkinter. I'm not very familiar with Tkinter actually. Right now, I want to implement an auto-save function, which runs alongside Tkinter's mainloop(), and save modified files automatically for every 5 minutes. I think I will need a second thread to do this. But I'm not sure how. Any ideas or examples will be much appreciated!! Thanks

回答1:

Just like the comment says, use 'after' recursion.

import Tkinter
root = Tkinter.Tk()

def autosave():
    # do something you want
    root.after(60000 * 5, autosave) # time in milliseconds

autosave() 
root.mainloop()

Threaded solution is possible too:

import threading
import time
import Tkinter

root = Tkinter.Tk()

def autosave():
    while True:
        # do something you want
        time.sleep(60 * 5)

saver = threading.Thread(target=autosave)
saver.start()
root.mainloop()

before leaving I use sys.exit() to kill all running threads and gui. Not sure is it proper way to do it or not.