python如何提供可视化界面,查看一个setting.txt文件每次修改的内容已及修改时间
时间: 2023-06-16 09:04:37 浏览: 142
Python可以通过Tkinter、PyQt、wxPython等GUI库来提供可视化界面。具体来说,可以使用以下步骤来实现你的需求:
1. 使用Tkinter或PyQt等GUI库创建一个窗口;
2. 在窗口中添加一个文本框,用于显示setting.txt文件的内容;
3. 使用Python的os模块的stat函数获取setting.txt文件的最后修改时间;
4. 在窗口中添加一个标签,用于显示setting.txt文件的最后修改时间;
5. 使用Python的watchdog模块监控setting.txt文件的变化;
6. 当文件发生变化时,更新文本框中的内容,并更新标签中的时间。
以下是一个使用Tkinter实现的示例代码:
```python
import tkinter as tk
import os
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class FileModifiedHandler(FileSystemEventHandler):
def __init__(self, text_widget, time_label):
super().__init__()
self.text_widget = text_widget
self.time_label = time_label
def on_modified(self, event):
if event.src_path == 'setting.txt':
with open('setting.txt', 'r') as f:
content = f.read()
self.text_widget.delete('1.0', tk.END)
self.text_widget.insert(tk.END, content)
mtime = os.stat('setting.txt').st_mtime
self.time_label.config(text='Last modified: ' + time.ctime(mtime))
class App:
def __init__(self, master):
self.master = master
master.title('Setting Viewer')
self.text_widget = tk.Text(master)
self.text_widget.pack(fill=tk.BOTH, expand=True)
mtime = os.stat('setting.txt').st_mtime
self.time_label = tk.Label(master, text='Last modified: ' + time.ctime(mtime))
self.time_label.pack(side=tk.BOTTOM)
event_handler = FileModifiedHandler(self.text_widget, self.time_label)
observer = Observer()
observer.schedule(event_handler, '.', recursive=False)
observer.start()
if __name__ == '__main__':
with open('setting.txt', 'r') as f:
content = f.read()
root = tk.Tk()
app = App(root)
app.text_widget.insert(tk.END, content)
app.text_widget.config(state=tk.DISABLED)
root.mainloop()
```
注意,以上代码需要安装watchdog模块,可以使用pip安装:
```
pip install watchdog
```
阅读全文
相关推荐


















