能用Python 写出一个比较完整参考代码吗?
时间: 2024-02-18 15:04:24 浏览: 66
PTA浙大版Python 程序设计题目集参考代码 PTA-Python-Answers
当然可以,下面是一个简单的参考代码,仅供参考:
```python
import tkinter as tk
from tkinter import filedialog
import re
import openpyxl
import datetime
import pickle
# 创建GUI界面
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
self.records = []
# 创建组件
def create_widgets(self):
self.file_label = tk.Label(self, text="选择txt文件:")
self.file_label.pack()
self.file_button = tk.Button(self, text="选择文件", command=self.choose_file)
self.file_button.pack()
self.listbox = tk.Listbox(self)
self.listbox.pack()
self.show_button = tk.Button(self, text="查看记录", command=self.show_record)
self.show_button.pack()
# 选择txt文件
def choose_file(self):
file_path = filedialog.askopenfilename()
if file_path:
data = self.extract_data(file_path)
if data:
self.save_record(data)
# 抽取数据
def extract_data(self, file_path):
with open(file_path, 'r') as f:
content = f.read()
pattern = re.compile(r'(\d+\.\d+)\s+(\d+\.\d+)\s+(\d+\.\d+)')
match = pattern.search(content)
if match:
data = match.groups()
return data
# 保存记录
def save_record(self, data):
now = datetime.datetime.now()
date_str = now.strftime("%Y-%m-%d %H:%M:%S")
record = {'time': date_str, 'data': data}
self.records.append(record)
self.listbox.insert(tk.END, date_str)
# 将记录保存到文件
with open('records.pkl', 'wb') as f:
pickle.dump(self.records, f)
# 显示记录
def show_record(self):
selection = self.listbox.curselection()
if selection:
index = selection[0]
record = self.records[index]
data = record['data']
tk.messagebox.showinfo('记录详情', f'排量: {data[0]}, 功率: {data[1]}, 扭矩: {data[2]}')
# 读取历史记录
def load_records():
try:
with open('records.pkl', 'rb') as f:
records = pickle.load(f)
return records
except:
return []
# 启动程序
def main():
root = tk.Tk()
app = Application(master=root)
app.records = load_records()
for record in app.records:
app.listbox.insert(tk.END, record['time'])
app.mainloop()
if __name__ == "__main__":
main()
```
这个程序实现了选择txt文件、抽取数据、保存记录、显示历史记录等功能,并将记录保存到了文件中。你可以根据自己的实际需求进行修改和完善。
阅读全文