使用 Python 和 Tkinter 实现自动保存功能 [英] Auto-save function implementation with Python and Tkinter

查看:112
本文介绍了使用 Python 和 Tkinter 实现自动保存功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个普遍的问题.我正在修改前同事编写的 Python 代码.代码的主要目的是

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

  1. 从本地读取一些文件
  2. 弹出一个 GUI 进行一些修改
  3. 将文件保存到本地

GUI 是用 Python 和 Tkinter 编写的.实际上,我对 Tkinter 不是很熟悉.现在,我想实现一个自动保存功能,它与 Tkinter 的 mainloop() 一起运行,并每 5 分钟自动保存一次修改过的文件.我想我需要第二个线程来做到这一点.但我不确定如何.任何想法或例子将不胜感激!谢谢

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

推荐答案

正如评论所说,使用 'after' 递归.

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()

在离开之前,我使用 sys.exit() 杀死所有正在运行的线程和 gui.不确定这样做是否正确.

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

这篇关于使用 Python 和 Tkinter 实现自动保存功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆