用tkinter写一个的账本
时间: 2023-09-30 17:09:42 浏览: 87
记事本:使用tkinter的记事本
好的,下面是一个简单的账本程序的Tkinter实现,包含添加记录、显示记录和保存记录的功能。
```python
import tkinter as tk
import json
class AccountBook:
def __init__(self):
self.records = []
def add_record(self, date, category, amount):
self.records.append({'date': date, 'category': category, 'amount': amount})
def get_records(self):
return self.records
def save_records(self, filename):
with open(filename, 'w') as f:
json.dump(self.records, f)
def load_records(self, filename):
with open(filename, 'r') as f:
self.records = json.load(f)
class AccountBookGUI:
def __init__(self, master, account_book):
self.master = master
self.account_book = account_book
self.master.title('账本')
self.master.geometry('300x300')
tk.Label(self.master, text='日期').grid(row=0, column=0)
tk.Label(self.master, text='类别').grid(row=0, column=1)
tk.Label(self.master, text='金额').grid(row=0, column=2)
self.date_entry = tk.Entry(self.master)
self.category_entry = tk.Entry(self.master)
self.amount_entry = tk.Entry(self.master)
self.date_entry.grid(row=1, column=0)
self.category_entry.grid(row=1, column=1)
self.amount_entry.grid(row=1, column=2)
tk.Button(self.master, text='添加记录', command=self.add_record).grid(row=2, column=0)
tk.Button(self.master, text='显示记录', command=self.show_records).grid(row=2, column=1)
tk.Button(self.master, text='保存记录', command=self.save_records).grid(row=2, column=2)
def add_record(self):
date = self.date_entry.get()
category = self.category_entry.get()
amount = self.amount_entry.get()
self.account_book.add_record(date, category, amount)
self.date_entry.delete(0, tk.END)
self.category_entry.delete(0, tk.END)
self.amount_entry.delete(0, tk.END)
def show_records(self):
records = self.account_book.get_records()
if len(records) == 0:
tk.messagebox.showinfo('消息', '没有记录')
else:
record_info = ''
for record in records:
record_info += f'{record["date"]} {record["category"]} {record["amount"]}\n'
tk.messagebox.showinfo('记录', record_info)
def save_records(self):
filename = tk.filedialog.asksaveasfilename(defaultextension='.json')
if filename:
self.account_book.save_records(filename)
tk.messagebox.showinfo('消息', '保存成功')
if __name__ == '__main__':
account_book = AccountBook()
root = tk.Tk()
app = AccountBookGUI(root, account_book)
root.mainloop()
```
这个程序使用了两个类,`AccountBook`类表示账本,包含添加记录、显示记录和保存记录的方法,`AccountBookGUI`类是Tkinter的GUI界面,包含添加记录、显示记录和保存记录的按钮。在主程序中创建`AccountBook`对象和`AccountBookGUI`对象,启动GUI界面。通过GUI界面添加账本记录,可以显示和保存记录。
注意,这个程序只是一个简单的示例,可以根据实际需要进行修改和完善。
阅读全文