Auto-save function implementation with Python and Tkinter

孤街浪徒 提交于 2019-12-08 11:45:58

问题


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.



来源:https://stackoverflow.com/questions/32114026/auto-save-function-implementation-with-python-and-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!