用python制作一个excel表,需要有界面,可以实现记账功能,可以输入输出收入支出,备注,名字,人员
时间: 2024-01-04 10:04:29 浏览: 116
好的,你可以使用Python的GUI库Tkinter来创建界面,使用第三方库openpyxl来操作Excel文件。以下是一个简单的示例代码,实现了记账功能:
```python
from tkinter import *
from tkinter import messagebox
from openpyxl import Workbook, load_workbook
import os
class ExpenseTracker:
def __init__(self, master):
self.master = master
master.title("Expense Tracker")
# 创建标签和输入框
Label(master, text="Name:").grid(row=0, column=0)
self.name_entry = Entry(master)
self.name_entry.grid(row=0, column=1)
Label(master, text="Person:").grid(row=1, column=0)
self.person_entry = Entry(master)
self.person_entry.grid(row=1, column=1)
Label(master, text="Amount:").grid(row=2, column=0)
self.amount_entry = Entry(master)
self.amount_entry.grid(row=2, column=1)
Label(master, text="Category:").grid(row=3, column=0)
self.category_entry = Entry(master)
self.category_entry.grid(row=3, column=1)
Label(master, text="Note:").grid(row=4, column=0)
self.note_entry = Entry(master)
self.note_entry.grid(row=4, column=1)
# 创建按钮
self.submit_button = Button(master, text="Submit", command=self.submit)
self.submit_button.grid(row=5, column=0)
self.clear_button = Button(master, text="Clear", command=self.clear)
self.clear_button.grid(row=5, column=1)
# 创建Excel文件(如果不存在)
if not os.path.exists("expense_tracker.xlsx"):
wb = Workbook()
ws = wb.active
ws.append(["Name", "Person", "Amount", "Category", "Note"])
wb.save("expense_tracker.xlsx")
def submit(self):
# 获取输入框中的值
name = self.name_entry.get()
person = self.person_entry.get()
amount = self.amount_entry.get()
category = self.category_entry.get()
note = self.note_entry.get()
# 验证输入是否合法
if not name or not person or not amount or not category:
messagebox.showerror("Error", "Please fill in all fields.")
return
try:
amount = float(amount)
except ValueError:
messagebox.showerror("Error", "Amount must be a number.")
return
# 将数据写入Excel文件
wb = load_workbook("expense_tracker.xlsx")
ws = wb.active
ws.append([name, person, amount, category, note])
wb.save("expense_tracker.xlsx")
# 清空输入框
self.clear()
# 提示保存成功
messagebox.showinfo("Success", "Data saved successfully.")
def clear(self):
self.name_entry.delete(0, END)
self.person_entry.delete(0, END)
self.amount_entry.delete(0, END)
self.category_entry.delete(0, END)
self.note_entry.delete(0, END)
root = Tk()
expense_tracker = ExpenseTracker(root)
root.mainloop()
```
这个程序会在当前目录下创建一个名为`expense_tracker.xlsx`的Excel文件,用于记录收支数据。每次输入数据后,会将数据追加到Excel文件的末尾。你可以根据自己的需求修改这个程序,例如添加查询、删除等功能。
阅读全文