在没有后台管理系统的时候,有时候为了方便起见,想提供一个输入框让运营人员直接输入,然后数据就会以数据库的形式存进数据库
效果图:
输入用户名
输入数据
输入信息后点击添加到表格,检查后方便批量保存到excel
代码
import tkinter as tk
from tkinter import ttk, messagebox, simpledialog, filedialog
from tkcalendar import DateEntry
import pandas as pd
import os# 全局变量保存用户名
cached_username = None# 保存到 Excel 的函数
def save_to_excel():table_name = table_name_var.get()if not table_name:messagebox.showwarning("输入错误", "请填写表名!")return# 获取表格数据rows = tree.get_children()if not rows:messagebox.showwarning("数据错误", "没有可保存的数据!")return# 收集表格数据new_data = []for row in rows:new_data.append(tree.item(row)["values"])# 转为 DataFramenew_df = pd.DataFrame(new_data, columns=["日期", "产品线", "SKU", "数量", "用户"])# 指定保存的文件路径file_path = filedialog.asksaveasfilename(defaultextension=".xlsx",filetypes=[("Excel Files", "*.xlsx")],title="选择保存路径",initialfile="database.xlsx")if not file_path:return# 检查文件是否存在并累加数据if os.path.exists(file_path):try:# 读取现有数据with pd.ExcelWriter(file_path, mode="a", engine="openpyxl", if_sheet_exists="overlay") as writer:existing_data = pd.read_excel(file_path, sheet_name=table_name, engine="openpyxl")combined_data = pd.concat([existing_data, new_df], ignore_index=True)combined_data.to_excel(writer, sheet_name=table_name, index=False)except Exception:# 如果工作表不存在,仅保存新数据with pd.ExcelWriter(file_path, mode="a", engine="openpyxl") as writer:new_df.to_excel(writer, sheet_name=table_name, index=False)else:# 文件不存在时创建新的 Excel 文件with pd.ExcelWriter(file_path, engine="openpyxl") as writer:new_df.to_excel(writer, sheet_name=table_name, index=False)# 成功提示messagebox.showinfo("保存成功", f"数据已保存到 {file_path} 的 {table_name} 表中。")tree.delete(*rows) # 清空表格# 添加数据到表格
def add_to_table():date = date_var.get()product_line = product_line_var.get()sku = sku_var.get()quantity = quantity_var.get()if not (date and product_line and sku and quantity):messagebox.showwarning("输入错误", "请填写所有字段!")returntry:# 验证数量为数字quantity = int(quantity)# 添加到表格(包括隐藏列)tree.insert("", "end", values=(date, product_line, sku, quantity, cached_username))# 清空输入框product_line_var.set("")sku_var.set("")quantity_var.set("")except ValueError:messagebox.showerror("输入错误", "数量必须是整数!")# 主程序启动
if __name__ == "__main__":# 弹出用户名输入框cached_username = simpledialog.askstring("用户名输入", "请输入用户名:")if not cached_username:messagebox.showerror("错误", "用户名不能为空,程序将退出!")exit()# 创建主窗口root = tk.Tk()root.title("批量数据处理窗口")# 表名输入tk.Label(root, text="表名:").grid(row=0, column=0, padx=10, pady=5, sticky="e")table_name_var = tk.StringVar()tk.Entry(root, textvariable=table_name_var, width=30).grid(row=0, column=1, padx=10, pady=5)# 日期选择tk.Label(root, text="日期:").grid(row=1, column=0, padx=10, pady=5, sticky="e")date_var = tk.StringVar()date_picker = DateEntry(root, textvariable=date_var, width=27, background="darkblue", foreground="white", borderwidth=2)date_picker.grid(row=1, column=1, padx=10, pady=5)# 产品线输入tk.Label(root, text="产品线:").grid(row=2, column=0, padx=10, pady=5, sticky="e")product_line_var = tk.StringVar()tk.Entry(root, textvariable=product_line_var, width=30).grid(row=2, column=1, padx=10, pady=5)# SKU输入tk.Label(root, text="SKU:").grid(row=3, column=0, padx=10, pady=5, sticky="e")sku_var = tk.StringVar()tk.Entry(root, textvariable=sku_var, width=30).grid(row=3, column=1, padx=10, pady=5)# 数量输入tk.Label(root, text="数量:").grid(row=4, column=0, padx=10, pady=5, sticky="e")quantity_var = tk.StringVar()tk.Entry(root, textvariable=quantity_var, width=30).grid(row=4, column=1, padx=10, pady=5)# 添加按钮tk.Button(root, text="添加到表格", command=add_to_table).grid(row=5, column=0, columnspan=2, pady=10)# 表格(Treeview)columns = ("日期", "产品线", "SKU", "数量", "用户")tree = ttk.Treeview(root, columns=columns, show="headings", height=10)# 显示前四列for col in columns[:-1]:tree.heading(col, text=col)tree.column(col, width=100, anchor="center")# 隐藏用户列tree.heading("用户", text="用户")tree.column("用户", width=0, anchor="center", stretch=False)tree.grid(row=6, column=0, columnspan=2, padx=10, pady=5)# 保存按钮tk.Button(root, text="保存到Excel", command=save_to_excel).grid(row=7, column=0, columnspan=2, pady=10)# 运行主循环root.mainloop()