百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

Python 门店会员管理系统V1.0 ——新手练手

zhezhongyun 2025-05-05 20:10 44 浏览

门店会员管理系统V1.0
目的:掌握控件的布局,左右,上下结构,掌握treeview控件的使用,绑定事件,掌握子窗体的调用,本想引入日历控件,但发现编译后运行起来不显示,查了说要打包的时候打包本地目录啥的,
后续有空再研究。
功能:
****1:会员管理 ****
新增、删除、修改,为会员充值,消费。
2:消费项目自定义,可以扩展为积分消费等,请自行扩展。
3:充值、消费查询
4:用户管理 考虑到可能一家门店有不同的店员需要管理,当然也可以弄权限,我没弄,有兴趣的自己去扩展
5:hashlib 实现简单的软件注册功能,绑定每台电脑的SN号
6:。。。。请自行扩展
先看一下整个系统:
默认用户名:admin,密码:123456


如果没注册的话,操作按钮将不可用。


全局功能模块来一张


1:会员管理





新增时有考虑到会员密码,做消费的时候可能需要会员输入密码验证之类的。
支持项目自定义
2:报表管理
分充值,消费,但充值和消费放在同一张表中,只是用类型区分,还有日报,月报,方便老板查看当日业绩,当月业绩

3:用户管理新增,删除,修改用户目前没实现权限控制,但够用就行4:软件注册软件本身没什么作用,做注册是为了做着玩的。破解也是很简单的。

以下为代码:
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from tkcalendar import DateEntry
import sqlite3
import hashlib
import time
import wmi
import win32com.client as win32
from PIL import Image, ImageTk
from datetime import datetime
from tkinter import simpledialog

class LoginWindow:
def
init(self):
self.window = tk.Tk()
self.window.title("用户登录")
# 初始化数据库
self.conn = sqlite3.connect('barbershop.db')
self.create_tables()
# 设置窗口大小
window_width = 300
window_height = 180

    # 获取屏幕尺寸
    screen_width = self.window.winfo_screenwidth()
    screen_height = self.window.winfo_screenheight()

    # 计算居中坐标
    x = (screen_width - window_width) // 2
    y = (screen_height - window_height) // 2

    # 应用几何布局 (格式: "宽x高±X±Y")
    self.window.geometry(f"{window_width}x{window_height}+{x}+{y}")
    self.window.resizable(False, False)    # 禁止调整窗口大小
    # self.window.attributes('-toolwindow', 1)  # 适用于Windows系统 隐藏最大化按钮,但可能保留最小化按钮
    # self.window.overrideredirect(True)  # 移除标题栏和系统按钮
    # 创建界面布局
    self.create_widgets()
def create_tables(self):

   """创建数据库表结构"""
   cursor = self.conn.cursor()
   # sql = """
   #         Delete from sys_mstr
   #       """
   # cursor.execute(sql)
   # self.conn.commit()
   # 数据库注册表
   c = wmi.WMI()
   sn = c.Win32_DiskDrive()[0].SerialNumber.strip()  # 硬盘序列号
   cursor.execute('''CREATE TABLE IF NOT EXISTS sys_mstr ( sys_sn TEXT PRIMARY KEY , sys_pwd TEXT, reg_date TEXT)''')
   sql = """
           INSERT OR IGNORE INTO sys_mstr ( sys_sn, sys_pwd,reg_date) VALUES (?, ?, ?)
         """
   params = (sn, '', datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
   cursor.execute(sql, params)
   self.conn.commit()

   # 初始化用户表 user_mstr 初始化管理员帐号admin,密码:666666
   cursor.execute('''CREATE TABLE IF NOT EXISTS User_mstr 
                    ( user_id TEXT PRIMARY KEY , user_name TEXT ,  user_password TEXT , reg_date TEXT )''')
   sql = """
             INSERT OR IGNORE INTO user_mstr ( user_id, user_name, user_password,reg_date) VALUES (?, ?, ?,?)
            """
   password='666666'
   #hashed_password = hashlib.sha256(password.encode()).hexdigest()
   params = ('admin', '管理员', password, datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
   cursor.execute(sql, params)
   self.conn.commit()

def create_widgets(self):
    #
    ttk.Label(self.window, text="门店会员管理系统",anchor="center" ,
            font = ("微软雅黑", 14, "bold"), foreground = "#333333", background = "#F5F0E0").grid(row=0, column=1,sticky="sw")
    # 用户名
    ttk.Label(self.window, text="用户名:",font = ("微软雅黑", 12)).grid(row=1, column=0, padx=10, pady=10)
    self.username_entry = ttk.Entry(self.window,font = ("微软雅黑", 12))
    self.username_entry.grid(row=1, column=1, padx=10, pady=10)
    self.username_entry.focus() # 用户名获取焦点
    # 先设为默认方便调试,后续正式启用的时候要放空,让用户输
    self.username_entry.insert(0, 'admin')
    # 密码
    ttk.Label(self.window, text="密 码:",font = ("微软雅黑", 12)).grid(row=2, column=0, padx=10, pady=10)
    self.password_entry = ttk.Entry(self.window, font = ("微软雅黑", 12),show="*")
    self.password_entry.grid(row=2, column=1, padx=10, pady=10)
    # 先设为默认方便调试,后续正式启用的时候要放空,让用户输
    self.password_entry.insert(0, '666666')
    # 按钮容器 Frame
    button_frame = ttk.Frame(self.window)
    button_frame.grid(row=3, column=1, sticky=tk.E, padx=10, pady=10)

    # 取消按钮
    cancel_btn = ttk.Button( button_frame, text="取消" ,command=self.window.destroy)  # 直接关闭窗口
    cancel_btn.pack(side=tk.RIGHT, padx=5)

    # 登录按钮
    login_btn = ttk.Button(button_frame,text="登录",command=self.login) # 绑定点击事件“登录”时跳转login
    login_btn.pack(side=tk.RIGHT)
    # 初始密码提示
    # ttk.Label(self.window, text="提示:管理员初始密码为‘666666’").grid(row=4, column=0, padx=10, pady=10)


def login(self):
    userid = self.username_entry.get()
    userpassword = self.password_entry.get()

    # 简单验证
    if not userid or not userpassword:
        messagebox.showerror("错误", "用户名和密码不能为空")
        return
    # 执行查询用户表中用户名和密码,验证是否合法登录
    try:
        cursor = self.conn.cursor()
        cursor.execute("SELECT user_id ,user_password  FROM user_mstr where user_id=?",(userid,))
        # 获取单条结果(唯一用户)
        result = cursor.fetchone()
        print(result)
        if result:
            user_id,user_password = result
            if userid == user_id and userpassword == user_password:
                self.window.destroy()  # 关闭登录窗口
                root = tk.Tk()  # 创建主窗口
                # self.conn.close() # 打开主界面前,关闭游标接
                MemberSystem(root)           # 打开主界面
            else:
                messagebox.showerror("提示", "用户名或密码错误")
        else:
            messagebox.showerror("提示", "用户名不存在")
    except sqlite3.Error as e:
           messagebox.showerror("错误", f"数据库查询失败: {str(e)}")
    finally:
           cursor.close()  # 关闭游标
def run(self):
    self.window.mainloop()

class MemberSystem():
def
init(self,root):
# 初始化数据库
self.conn = sqlite3.connect('barbershop.db')
self.create_tables()
# 主窗口设置
self.root = root
self.root.title("门店会员管理系统-Author: Running ver:1.0")
self.root.geometry("1100x600")
self.root.state('zoomed') # 最大化窗口
# 创建左右布局
self.create_left_menu()
self.create_right_content()
self.init_styles()
self.systime()
def systime(self):
"实时刷新显示日期时间"
current_time = time.strftime('%Y-%m-%d %H:%M:%S')
self.root.title("门店会员管理系统-Author: Running ver:1.0;当前时间:" + current_time )
self.root.after(1000, self.systime)

def get_baseboard_sn(self):
    # 获取硬盘序列号
    c = wmi.WMI()
    # 硬盘序列号
    sn = c.Win32_DiskDrive()[0].SerialNumber.strip()  # 硬盘序列号
    return sn
def create_subwindow(self):
    # 创建子窗口
    subwindow = tk.Toplevel(self.root)
    # 计算居中位置
    self.root.update_idletasks()  # 强制更新窗口几何信息
    parent_x = self.root.winfo_x()
    parent_y = self.root.winfo_y()
    parent_width = self.root.winfo_width()
    parent_height = self.root.winfo_height()
    child_width = 420  # 子窗口固定宽度
    child_height = 100  # 子窗口固定高度

    # 计算子窗口左上角坐标
    x = parent_x + (parent_width - child_width) // 2
    y = parent_y + (parent_height - child_height) // 2

    # 设置子窗口位置
    subwindow.geometry(f"+{x}+{y}")
    subwindow.configure(bg='#d3fbfb')
    subwindow.resizable(width=False, height=False)
    subwindow.attributes("-toolwindow", 2)
    return subwindow

def Open_regdit(self):
    """打开弹出窗口的注册界面"""
    winNew = self.create_subwindow()
    winNew.title('软件注册->联系作者QQ:124068151')
    # 放2个标签Label 和2个单行输入框entry
    l_user = tk.Label(winNew, text='序列号:', font=('宋体', 12), bg='#d3fbfb')
    l_psw = tk.Label(winNew, text='注册码:', font=('宋体', 12), bg='#d3fbfb')
    l_label = tk.Label(winNew, text='', font=('宋体', 18), bg='#d3fbfb')
    add_entry_userid = tk.StringVar()
    add_entry_userid = tk.Entry(winNew, textvariable=add_entry_userid, width=40, font=('宋体', 12), state=tk.NORMAL)
    add_entry_psw = tk.StringVar()
    add_entry_psw = tk.Entry(winNew, textvariable=add_entry_psw, width=40, font=('宋体', 12))
    add_entry_userid.insert(0, self.get_baseboard_sn())
    # 控件布局
    l_user.grid(row=0, column=1)
    l_psw.grid(row=1, column=1)
    l_label.grid(row=3,column=1)
    add_entry_userid.grid(row=0, column=2)
    add_entry_psw.grid(row=1, column=2)
    # 获取系统自动生成的序列号和注册码
    SNsys_temp = self.get_baseboard_sn()
    MDsys = hashlib.md5()
    SNsys = 'lqw' + SNsys_temp
    MDsys.update(SNsys.encode(encoding='utf-8'))
    MDsys.hexdigest()

    def Regdit():
        # 获取用户输入的序列号和注册码和系统的进行比较
        SN = add_entry_userid.get()
        MD = add_entry_psw.get()
        # print('用户序列号'+SN+'用户注册码:'+MD)
        # print('系统序列号'+SNsys+'系统注册码:'+MDsys.hexdigest())
        if MD == '':
            messagebox.showinfo('提示', '请输入注册码!')
            return
        elif SN == '':
            messagebox.showinfo('提示', '序列号不能为空!')
            return
        elif SN != SNsys_temp:
            messagebox.showinfo('提示', '序列号错误!')
            return
        elif MD != MDsys.hexdigest():
            messagebox.showinfo('提示', '序列号和注册码不匹配,注册失败!')
            return
        # 写入配置文件JSON
        if not MD or not SN:
            messagebox.showerror("提示", "请填写完整的注册信息!")
            return
        try:
            cursor = self.conn.cursor()
            sql = """
                     UPDATE sys_mstr 
                     SET sys_pwd=?, reg_date=?
                     WHERE sys_sn=?
                 """
            parms = (MD, datetime.now().strftime("%Y-%m-%d %H:%M:%S"), SN)
            cursor.execute(sql, parms)
            self.conn.commit()
            messagebox.showinfo('提示', '注册成功,感谢您的使用!')
            winNew.destroy()
        except sqlite3.IntegrityError:
            messagebox.showerror("错误", "注册失败请联系作者!")
    def exit():
        winNew.destroy()

    # 放两个按钮
    b_submit = tk.Button(winNew, text='注 册', command=Regdit, bg='#d3fbfb')
    b_cancel = tk.Button(winNew, text='退 出', command=exit, bg='#d3fbfb')
    # b_submit.grid(row=3, column=1,padx=25)
    # b_cancel.grid(row=3, column=2,padx=45)
    b_submit.place(relx=0.3, y=50, relheight=0.30, width=60)
    b_cancel.place(relx=0.6, y=50, relheight=0.30, width=60)
def create_tables(self):

   """创建数据库表结构"""
   cursor = self.conn.cursor()
   # 服务项目表
   cursor.execute('''CREATE TABLE IF NOT EXISTS trans_set ( trans_id TEXT PRIMARY KEY , trans_name TEXT, trans_price REAL DEFAULT 0.0,trans_remark TEXT,  date TEXT)''')
   # 会员信息表
   cursor.execute('''CREATE TABLE IF NOT EXISTS members ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL,  phone TEXT UNIQUE NOT NULL, password TEXT DEFAULT '', balance REAL DEFAULT 0.0 , points INTEGER DEFAULT 0, remark TEXT DEFAULT '',reg_date TEXT)''')
   # 交易记录表
   cursor.execute('''CREATE TABLE IF NOT EXISTS transactions ( id INTEGER PRIMARY KEY AUTOINCREMENT, member_id INTEGER, amount REAL, type TEXT, description TEXT,  date TEXT)''')
   self.conn.commit()
def init_styles(self):
    """初始化Treeview样式"""
    self.style = ttk.Style()
    # 常规行样式
    self.style.configure("Treeview",
                         font=("微软雅黑", 12),  # 字体设置
                         foreground="#333333",  # 文字颜色 黑
                         background="#FFFFFF",  # 背景色
                         rowheight=25)  # 行高

    # 标题栏样式
    # "coral"  珊瑚色(柔和的橙红色),"tomato"  番茄红(比红色更温暖),"salmon"  三文鱼粉(浅橙粉色)"orangered" ,橙红色(高饱和度)"chocolate" 巧克力色(深棕色)
    self.style.configure("Treeview.Heading",
                         font=("微软雅黑", 14, "bold"),  # 加粗字体
                         foreground="darkslategray",  # 文字颜色
                         background="#F5F0E0",  # 标题背景色
                         relief="flat")  # 扁平化样式

    # 选中项样式
    self.style.map("Treeview",
                   background=[('selected', '#0078D7')], # 选中背景色
                   foreground=[('selected', 'white')])  # 选中文字颜色
    # 滚动条样式
    self.style.configure("Vertical.TScrollbar",
                         background="lightgray",  # 滚动条颜色
                         troughcolor="white",  # 滚动条轨道颜色
                         arrowsize=25  # 箭头大小
                         )
def create_calendar(self):
    global  cal
    # 创建日期选择框
    cal = DateEntry(self.top_right_frame,width=12,date_pattern="yyyy-mm-dd",  background="darkblue",  foreground="white")
    #cal.grid(row=0, column=0)
def create_left_menu(self):
    """创建左侧菜单树"""
    # 左侧框架(导航栏)
    self.left_frame = ttk.Frame(self.root, width=200)
    self.left_frame.pack(side=tk.LEFT, fill=tk.Y, padx=5, pady=5)
    self.tree = ttk.Treeview(self.left_frame, show='tree headings',style="Treeview")
    # 设置列(使用默认的 #0 列)
    self.tree.heading("#0", text="系统菜单")  # 设置列标题
    self.tree.column("#0", width=200, anchor="w")  # 设置列宽和对齐方式
    self.tree.pack(expand=True, fill="both")
    # 定义主菜单和子菜单的映射关系
    menu_hierarchy = {
                        "会员管理": ["会员查询", "会员充值","会员消费"],
                        "报表查询": ["充值查询", "消费查询", "充消日报","充消月报"],
                        "用户管理": ["用户查询","权限设置", "角色分配"],
                        "参数设置": ["项目设置", "折扣规则","软件注册"],
                        "系统日志": ["操作日志", "登录日志", "错误日志"],
                        "退出系统": []  # 没有子菜单
                     }
    menu_descriptions = {
        "会员管理": "管理会员的增删改查操作","会员查询": "根据条件查询会员信息","会员充值": "为会员账户进行充值操作","会员消费": "记录会员消费记录",
        "报表查询": "查看各类统计报表","充值查询": "查询充值历史记录","消费查询": "查询消费历史记录","充消日报": "生成每日统计报表","充消月报": "生成月度汇总报表",
        "参数设置": "系统参数配置","项目设置": "管理提供的服务项目","折扣规则": "配置会员折扣规则","软件注册": "支持作者创作请注册",
        "用户管理": "管理后台用户和权限","用户查询": "根据条件查询会员信息","权限设置": "配置用户权限","角色分配": "分配用户角色",
        "系统日志": "查看系统操作记录","操作日志": "查看用户操作日志","登录日志": "查看用户登录记录","错误日志": "查看系统错误信息",
        "退出系统": "退出应用程序"
    }
    for main_menu, sub_menus in menu_hierarchy.items():
        main_menu_id = self.tree.insert("", "end", text=main_menu, values=(menu_descriptions.get(main_menu, "暂无描述"),)) #values=(main_menu),
        # 为该主菜单插入子菜单
        for sub_menu in sub_menus:
            self.tree.insert(main_menu_id, "end", text=sub_menu, values=(menu_descriptions.get(sub_menu, "暂无描述"),)) # values=(sub_menu),) ,

    # 绑定菜单点击事件
    self.tree.bind("<<TreeviewSelect>>", self.on_menu_select)
    self.tree.bind("<Button-1>", self.on_menu_click)

def create_right_content(self):
    """创建右侧内容区域"""
    global info_label,title_label,btn_add,btn_delete,btn_modify,btn_recharge,btn_consume,search_entry
    self.right_frame = ttk.Frame(self.root)
    self.right_frame.pack(side="right", expand=True, fill="both")
    #将右侧区域分为上下两部分
    # 右上的子区域
    self.top_right_frame = tk.Frame(self.right_frame,height=5)
    self.top_right_frame.pack(side=tk.TOP, fill=tk.X)  # 上方扩展填充
    #self.create_calendar()
    # 右上区域的查找区域
    ttk.Label(self.top_right_frame, text="模糊查找:").grid(row=0, column=1)
    search_entry = ttk.Entry(self.top_right_frame, width=30)
    search_entry.grid(row=0, column=2, padx=5)
    search_entry.bind('<KeyRelease>', self.search_member)
    info_label = ttk.Label(self.top_right_frame, text="菜单功能:",font=("微软雅黑", 10,"bold"),foreground="blue",
                           background="#F5F0E0") # 操作信息提示label
    info_label.grid(row=0, column=9)
    # 右上区域的操作按钮
    # 1. 用 Pillow 加载并调整图像大小
    # pil_image = Image.open("image/logo2.gif")  # 替换为你的图标路径
    # target_size = (32, 32)  # 设定目标尺寸 (宽度, 高度)
    # resized_image = pil_image.resize(target_size, Image.LANCZOS)  # 高质量缩放
    # # 2. 转换为 Tkinter 可用的 PhotoImage
    # icon = ImageTk.PhotoImage(resized_image)
    if self.top_right_frame.winfo_exists():
        btn_add = ttk.Button(self.top_right_frame, text="新增", command=self.show_add_member)
        btn_delete = ttk.Button(self.top_right_frame, text="删除", command=self.show_del_member)
        btn_modify = ttk.Button(self.top_right_frame, text="修改", command=self.show_mod_member)
        btn_recharge = ttk.Button(self.top_right_frame, text="充值", command=self.show_recharge)
        btn_consume = ttk.Button(self.top_right_frame, text="消费", command=self.show_consume)
        btn_rc = ttk.Button(self.top_right_frame, text="交易记录", command=self.show_transactions)
    # 添加横线
    separator = ttk.Separator(self.right_frame, orient=tk.HORIZONTAL)
    separator.pack(fill=tk.X, pady=1)  # pady 控制横线上下间距
    # 右下的子区域,一开始显示主界面 show_bottom_right_frame_main
    self.show_bottom_right_frame_main()
def show_bottom_right_frame_main(self):
    # 右下的子区域,系统一进来的时候显示“欢迎界面之类”或加载图片 加载图片(仅支持 GIF、PGM/PPM)
    self.bottom_right_frame = tk.Frame(self.right_frame, bg="#F5F0E0", height=450)
    if self.bottom_right_frame.winfo_exists():
        self.image = tk.PhotoImage(file="image/logo.gif")  # 替换为你的图片路径
        # 将图片添加到 Label 组件
        title_label = ttk.Label(self.bottom_right_frame, text="欢迎使用门店会员管理系统V1.0", anchor="center",
                  font=("微软雅黑", 40, "bold"), foreground="#333333", background="#F5F0E0")
        title_label.grid(row=0, column=0, sticky="nsew")
        img_label = ttk.Label(self.bottom_right_frame, image=self.image)
        img_label.grid(row=1,column=0, sticky="nsew")
        self.bottom_right_frame.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)  # 下方扩展填充

def resize_image(self, event):
    # 计算缩放后尺寸(保留20px边距)
    new_width = event.width - 20
    new_height = int(event.height * 0.7)  # 图片占窗口高度的70%

    resized_img = self.original_image.resize(
        (new_width, new_height),
        Image.Resampling.LANCZOS  # 高质量缩放
    )
    self.image = ImageTk.PhotoImage(resized_img)
    self.img_label.configure(image=self.image)
def on_double_click(self, event):
    """双击行触发打开修改函数窗口show_mod_member()"""
    self.show_mod_member()

def on_menu_click(self, event):
    region = self.tree.identify_region(event.x, event.y)
    if region == "heading":
        column = self.tree.identify_column(event.x)
        print(f"点击了左侧树的标题行")
    elif region == "cell":
        # 处理数据行点击逻辑
        item = self.tree.identify_row(event.y)
        print(f"点击了左侧树的数据行:{item}")
def on_menu_select(self, event):
    """菜单选择事件处理"""
    #print(create_yn)
    # 获取菜单文本和描述(values 的第一个元素)
    item = self.tree.selection()
    menu_text = self.tree.item(item, "text")
    menu_desc = self.tree.item(item, "values")
    info_label.config(text="菜单功能:"+f"{menu_desc}")  # 更新右侧 Label
    self.menu_actions = {
        "会员管理": {
            "add": lambda: self.show_add_member(), # 绑定会员删除函数
            "delete": lambda: self.show_del_member(),
            "modify": lambda: self.show_mod_member()
        },
        "用户管理": {
            "add": lambda: print("新增用户"),
            "delete": lambda: print("删除用户"),
            "modify": lambda: print("修改用户")
        },
        "项目设置": {
            "add": lambda: self.show_add_trans_item(),
            "delete": lambda: self.show_del_trans_item(),
            "modify": lambda: self.show_mod_trans_item()
        }
    }
    actions = self.menu_actions.get(menu_text, {})
    # 动态更新按钮属性
    # left_text2 = menu_text[:2] 取菜单text的前2位
    if menu_text=="会员管理" or menu_text=="用户管理" or menu_text=="项目设置":
        self.update_buttons(
            add_text = f"新增{menu_text[:2]}",
            add_cmd = actions.get("add", lambda: print("无操作")),
            del_text = f"删除{menu_text[:2]}",
            del_cmd = actions.get("delete", lambda: print("无操作")),
            modify_text = f"修改{menu_text[:2]}",
            modify_cmd = actions.get("modify", lambda: print("无操作"))
            )

    # 清空右下侧区域
    self.clear_widget() # 函数 clear_widget
    # 连接注册表判断软件是否已经注册,不注册的话,按钮不可点击,注册后可设置按钮可点击操作
    cursor = self.conn.cursor()
    SN = self.get_baseboard_sn()
    cursor.execute("SELECT sys_pwd FROM sys_mstr where sys_sn=?",(SN,))
    for item in cursor.fetchone():
        sys_pwd = item
        if not sys_pwd:
            info_label.config(text="提示:当前软件未注册,相关操作按钮不可用!")
            btn_add.config(state=tk.DISABLED)
            btn_delete.config(state=tk.DISABLED)
            btn_modify.config(state=tk.DISABLED)
            btn_recharge.config(state=tk.DISABLED)
            btn_consume.config(state=tk.DISABLED)
        else:
            btn_add.config(state=tk.NORMAL)
            btn_delete.config(state=tk.NORMAL)
            btn_modify.config(state=tk.NORMAL)
            btn_recharge.config(state=tk.NORMAL)
            btn_consume.config(state=tk.NORMAL)
        cursor.close()
    # 根据菜单显示不同内容
    print(menu_text)
    btn_add.grid_remove()
    btn_delete.grid_remove()
    btn_modify.grid_remove()
    btn_recharge.grid_remove() # 隐藏右上的"充值"按钮
    btn_consume.grid_remove()  # 隐藏右上的"消费"按钮
    # cal.grid_remove() # 隐藏右上的日历控件
    if menu_text == "会员管理" or menu_text == "用户管理" or menu_text=="报表查询" or menu_text=="参数设置" or menu_text=="系统日志":
        self.bottom_right_frame.destroy() #先销毁右下显示界面
        self.show_bottom_right_frame_main() # 再显示主界面
    elif menu_text=="会员查询" or menu_text=="会员充值" or menu_text=="会员消费":
        btn_add.grid(row=0, column=3, padx=5) # 显示右上的"新增会员"按钮
        btn_delete.grid(row=0, column=4, padx=5) # 显示右上的"删除会员"按钮
        btn_modify.grid(row=0, column=5, padx=5) # 显示右上的"修改会员"按钮
        btn_recharge.grid(row=0, column=6, padx=5)  # 显示右上的"充值"按钮
        btn_consume.grid(row=0, column=7, padx=5) # 显示右上的"消费"按钮
        self.show_member_management() # 显示全部会员列表
    elif menu_text == "充消日报" or menu_text == "充消月报":
        btn_add.grid_remove() # 隐藏右上的"新增会员"按钮
        btn_delete.grid_remove() # 隐藏右上的"删除会员"按钮
        btn_modify.grid_remove() # 隐藏右上的"修改会员"按钮
        btn_recharge.grid_remove()  # 隐藏右上的"充值"按钮
        btn_consume.grid_remove()  # 隐藏右上的"消费"按钮
        self.create_calendar() # 显示日历控件
        cal.grid(row=0, column=0)
    elif menu_text=="用户查询" or menu_text=="权限设置" or menu_text=="角色分配":
        btn_add.grid(row=0, column=3, padx=5) # 显示右上的"新增会员"按钮
        btn_delete.grid(row=0, column=4, padx=5) # 显示右上的"删除会员"按钮
        btn_modify.grid(row=0, column=5, padx=5) # 显示右上的"修改会员"按钮
        btn_recharge.grid_remove()  # 隐藏右上的"充值"按钮
        btn_consume.grid_remove()  # 隐藏右上的"消费"按钮
        self.show_user_management() # 显示全部用户列表
    elif menu_text == "项目设置":
        btn_add.grid(row=0, column=3, padx=5) # 显示右上的"新增项目"按钮
        btn_delete.grid(row=0, column=4, padx=5) # 显示右上的"删除项目"按钮
        btn_modify.grid(row=0, column=5, padx=5) # 显示右上的"修改项目"按钮
        btn_recharge.grid_remove()  # 隐藏右上的"充值"按钮
        btn_consume.grid_remove()  # 隐藏右上的"消费"按钮
        self.show_trans_items()  # 显示服务项目列表
    elif menu_text =="充值查询" or menu_text =="消费查询":
        self.show_trans_list()
    elif menu_text =="软件注册":
        self.Open_regdit()
    elif menu_text == "退出系统":
        self.root.destroy()
    else:
        btn_recharge.grid_remove()
        btn_consume.grid_remove()
        messagebox.showinfo("提示", f"此菜单功能正在开发中")
def clear_widget(self):
    for widget in self.bottom_right_frame.winfo_children():
        widget.destroy()
def update_buttons(self, add_text, add_cmd, del_text, del_cmd, modify_text, modify_cmd):
    """安全更新按钮属性和命令"""
    # 检查控件是否存在
    if btn_add.winfo_exists() and btn_add is not None:
       btn_add.config(text=add_text, command=add_cmd)
    if btn_delete.winfo_exists() and btn_delete is not None:
       btn_delete.config(text=del_text, command=del_cmd)
    if btn_modify.winfo_exists() and btn_modify is not None:
       btn_modify.config(text=modify_text, command=modify_cmd)
#===========================会员管理相关====================
def show_member_management(self):

    """加载会员列表"""
    global columns,tree
    columns = ('会员ID','姓名','电话','余额','密码','备注','注册日期')
    tree = ttk.Treeview(self.bottom_right_frame, columns=columns, show="headings")
    # 绑定双击事件
    # self.tree.bind("<Double-1>", self.on_double_click)
    # 设置列标题和宽度
    for col in columns:
        tree.heading(col, text=col)
        tree.column(col, width=50,anchor="center") # 列居中对齐
    # 删除行数据
    for row in tree.get_children():
        tree.delete(row)
    # 连接表查询出数据
    cursor = self.conn.cursor()
    cursor.execute("SELECT id, name, phone, balance , password ,remark , reg_date FROM members")
    # 添加数据
    for member in cursor.fetchall():
        id, name, phone, balance, password, remark, reg_date = member
        tree.insert('',tk.END,values=(id,name,phone,balance,'******',remark,reg_date),tags='')
        #tree.insert('', tk.END, values=member)
    tree.pack(side=tk.LEFT,expand=True, fill=tk.BOTH)
    #添加滚动条
    scrollbar = ttk.Scrollbar(self.bottom_right_frame, orient=tk.VERTICAL, command=tree.yview,style="Vertical.TScrollbar")
    tree.configure(yscrollcommand=scrollbar.set)
    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    # 绑定双击事件
    tree.bind("<Double-1>", self.on_double_click)
def show_add_member(self):

   """显示添加会员窗口"""
   self.add_window = tk.Toplevel(self.root)
   self.add_window.title("添加新会员")
   self.add_window.resizable(False, False)  # 禁止调整窗口大小
   ttk.Label(self.add_window, text="姓名:").grid(row=0, column=0, padx=5,pady=5)
   self.name_entry = ttk.Entry(self.add_window,width=20)
   self.name_entry.grid(row=0, column=1)
   ttk.Label(self.add_window, text="电话:").grid(row=1, column=0, padx=5,pady=5)
   self.phone_entry = ttk.Entry(self.add_window,width=20)
   self.phone_entry.grid(row=1, column=1)
   ttk.Label(self.add_window, text="密码:").grid(row=2, column=0, padx=5,pady=5)
   self.password_entry = ttk.Entry(self.add_window,width=20)
   self.password_entry.grid(row=2, column=1)
   ttk.Button(self.add_window, text="保存", command=self.save_member).grid(row=3, column=0,columnspan=2, pady=10)
   # 计算居中位置
   self.root.update_idletasks()  # 强制更新窗口几何信息
   parent_x = self.root.winfo_x()
   parent_y = self.root.winfo_y()
   parent_width = self.root.winfo_width()
   parent_height = self.root.winfo_height()
   child_width = 200  # 子窗口固定宽度
   child_height = 150  # 子窗口固定高度

   # 计算子窗口左上角坐标
   x = parent_x + (parent_width - child_width) // 2
   y = parent_y + (parent_height - child_height) // 2

   # 设置子窗口位置
   self.add_window.geometry(f"+{x}+{y}")
def save_member(self):

    """处理保存新会员信息"""
    name = self.name_entry.get()
    phone = self.phone_entry.get()
    password = self.password_entry.get()
    if not name or not phone:
        messagebox.showerror("错误","请填写完整信息")
        return
    try:
        cursor = self.conn.cursor()
        sql = """
              INSERT INTO members (name, phone, password,reg_date) VALUES (?, ?, ?,?)
             """
        params = ( name,phone,password,datetime.now().strftime("%Y-%m-%d %H:%M:%S") )
        cursor.execute(sql,params)
        self.conn.commit()
        self.add_window.destroy()
        messagebox.showinfo("成功","会员添加成功")
        self.load_members() # 添加成功后刷新会员列表
    except sqlite3.IntegrityError:
        messagebox.showerror("错误","该电话号码已存在")
def show_del_member(self):

    """显示删除会员窗口"""
    #messagebox.showinfo("提示", "该功能尚未提供")
    selected = tree.focus()
    if not selected:
        messagebox.showerror("错误", "请先选择会员")
        return
    amount = tree.item(selected)['values'][3]  # 余额
    if  float(amount) > 0.0:
        messagebox.showerror("错误", "会员还有可用余额不可删除")
        return
    try:
        member_id = tree.item(selected)['values'][0]
        cursor = self.conn.cursor()
        sql='''Delete FROM members WHERE id = ?  '''
        cursor.execute(sql,(member_id,))
        self.conn.commit()
        self.load_members()
        messagebox.showinfo("成功","会员删除成功")
    except sqlite3.IntegrityError:
        messagebox.showerror("错误","会员删除失败")
        return
def show_mod_member(self):

    """显示修改会员窗口"""
    selected = tree.focus()
    if not selected:
        messagebox.showerror("错误", "请先选择会员")
        return
    name = tree.item(selected)['values'][1] #姓名
    phone = tree.item(selected)['values'][2]  # 电话
    acount = tree.item(selected)['values'][3]  # 余额能改?业务尚不明确
    password = tree.item(selected)['values'][4]  # 密码
    self.mod_window = tk.Toplevel(self.root)
    self.mod_window.title("修改会员信息")
    self.mod_window.resizable(False, False)  # 禁止调整窗口大小
    ttk.Label(self.mod_window, text="姓名:").grid(row=0, column=0, padx=5, pady=5)
    self.name_entry = ttk.Entry(self.mod_window, textvariable=name, width=20)
    self.name_entry.grid(row=0, column=1)
    ttk.Label(self.mod_window, text="电话:").grid(row=1, column=0, padx=5, pady=5)
    self.phone_entry = ttk.Entry(self.mod_window, textvariable=phone, width=20)
    self.phone_entry.grid(row=1, column=1)
    ttk.Label(self.mod_window, text="密码:").grid(row=2, column=0, padx=5, pady=5)
    self.password_entry = ttk.Entry(self.mod_window, textvariable=password, width=20)
    self.password_entry.grid(row=2, column=1)
    # 姓名,电话,密码赋值
    self.name_entry.insert(0,name)
    self.phone_entry.insert(0,phone)
    self.password_entry.insert(0,password)
    ttk.Button(self.mod_window, text="保存", command=self.update_member).grid(row=3, column=0, columnspan=2, pady=10)
    # 计算居中位置
    self.root.update_idletasks()  # 强制更新窗口几何信息
    parent_x = self.root.winfo_x()
    parent_y = self.root.winfo_y()
    parent_width = self.root.winfo_width()
    parent_height = self.root.winfo_height()
    child_width = 200  # 子窗口固定宽度
    child_height = 150  # 子窗口固定高度

    # 计算子窗口左上角坐标
    x = parent_x + (parent_width - child_width) // 2
    y = parent_y + (parent_height - child_height) // 2

    # 设置子窗口位置
    self.mod_window.geometry(f"+{x}+{y}")
def update_member(self):

    """处理修改的会员信息"""
    selected = tree.focus()
    id = tree.item(selected)['values'][0]  # 会员ID
    name = self.name_entry.get()
    phone = self.phone_entry.get()
    password = self.password_entry.get()
    if not name or not phone:
        messagebox.showerror("错误","请填写完整信息")
        return
    try:
        cursor = self.conn.cursor()
        sql = """
            UPDATE members 
            SET name=?, phone=?, password=?, reg_date=?
            WHERE id=?
        """
        parms = ( name, phone,password,datetime.now().strftime("%Y-%m-%d %H:%M:%S"),id )
        cursor.execute(sql,parms)
        self.conn.commit()
        self.mod_window.destroy()
        self.load_members() # 修改成功后刷新会员列表
        messagebox.showinfo("成功","会员修改成功")
    except sqlite3.IntegrityError:
        messagebox.showerror("错误","该电话号码已存在")
def load_members(self):

  """加载会员列表"""
  for row in tree.get_children():
      tree.delete(row)
  cursor = self.conn.cursor()
  cursor.execute(
    "SELECT id, name, phone, balance,'******',remark,reg_date FROM members")
  for member in cursor.fetchall():
      tree.insert('', tk.END, values=member)
def reload_members(self):
    """刷新会员列表"""
    for item in self.trans_tree.get_children():
        self.trans_tree.delete(item)

    for member in self.members:
        self.trans_tree.insert("", "end", values=(
            member["id"],
            member["name"],
            member["balance"]
        ))
def search_member(self, event=None):

    """搜索会员 模糊查找,根据ID,姓名,电话"""
    query = search_entry.get()
    cursor = self.conn.cursor()
    cursor.execute(
                "SELECT id, name, phone, balance FROM members WHERE name LIKE ? OR phone LIKE ?",
                 (f'%{query}%',f'%{query}%'))
    tree.delete(*tree.get_children())
    for item in cursor.fetchall():
        tree.insert('', tk.END,values=item)
def search_trans(self, event=None):

    """搜索会员 模糊查找,根据ID,姓名,电话"""
    query = search_entry.get()
    cursor = self.conn.cursor()
    cursor.execute("SELECT member_id, name, phone,amount, type, description, date "
                   "FROM transactions,members  where transactions.member_id = members.id "
                   "and name like ? or phone like ? or description like ?",
                   (f'%{query}%', f'%{query}%',f'%{query}%'))
    tree.delete(*tree.get_children())
    for item in cursor.fetchall():
        tree.insert('', tk.END,values=item)
def cancel_member(self):
    self.add_window.destroy()
# ==========================服务项目设置相关=================
def show_trans_items(self):
    """加载服务项目列表"""
    global columns,tree
    columns = ('项目ID','项目名称','项目价格','备注')
    tree = ttk.Treeview(self.bottom_right_frame, columns=columns, show="headings")
    # 设置列标题和宽度
    for col in columns:
        tree.heading(col, text=col)
        tree.column(col, width=50,anchor="center") # 列居中对齐
    # 删除行数据
    for row in tree.get_children():
        tree.delete(row)
    # 连接表查询出数据
    cursor = self.conn.cursor()
    cursor.execute("SELECT trans_id, trans_name, trans_price,trans_remark FROM trans_set")
    # 添加数据
    for trans_item in cursor.fetchall():
        trans_id, trans_name, trans_price, trans_remark = trans_item
        tree.insert('',tk.END,values=trans_item,tags='')
    tree.pack(side=tk.LEFT,expand=True, fill=tk.BOTH)
    #添加滚动条
    scrollbar = ttk.Scrollbar(self.bottom_right_frame, orient=tk.VERTICAL, command=tree.yview,style="Vertical.TScrollbar")
    tree.configure(yscrollcommand=scrollbar.set)
    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
def show_add_trans_item(self):

   """显示添加服务项目窗口"""
   self.add_window = tk.Toplevel(self.root)
   self.add_window.title("添加新项目")
   self.add_window.resizable(False, False)  # 禁止调整窗口大小
   ttk.Label(self.add_window, text="项目ID:").grid(row=0, column=0, padx=5,pady=5)
   self.id_entry = ttk.Entry(self.add_window,width=20)
   self.id_entry.grid(row=0, column=1)
   ttk.Label(self.add_window, text="项目名称:").grid(row=1, column=0, padx=5,pady=5)
   self.name_entry = ttk.Entry(self.add_window,width=20)
   self.name_entry.grid(row=1, column=1)
   ttk.Label(self.add_window, text="项目价格:").grid(row=2, column=0, padx=5,pady=5)
   self.price_entry = ttk.Entry(self.add_window,width=20)
   self.price_entry.grid(row=2, column=1)
   ttk.Label(self.add_window, text="项目备注:").grid(row=3, column=0, padx=5,pady=5)
   self.remark_entry = ttk.Entry(self.add_window,width=20)
   self.remark_entry.grid(row=3, column=1)
   ttk.Button(self.add_window, text="保存", command=self.save_trans_item).grid(row=4,column=0,columnspan=2, pady=10)
   # 计算居中位置
   self.root.update_idletasks()  # 强制更新窗口几何信息
   parent_x = self.root.winfo_x()
   parent_y = self.root.winfo_y()
   parent_width = self.root.winfo_width()
   parent_height = self.root.winfo_height()
   child_width = 200  # 子窗口固定宽度
   child_height = 200  # 子窗口固定高度

   # 计算子窗口左上角坐标
   x = parent_x + (parent_width - child_width) // 2
   y = parent_y + (parent_height - child_height) // 2

   # 设置子窗口位置
   self.add_window.geometry(f"+{x}+{y}")
def save_trans_item(self):

    """处理保存新项目信息"""
    trans_id = self.id_entry.get()
    trans_name = self.name_entry.get()
    trans_price = self.price_entry.get()
    trans_remark = self.remark_entry.get()
    if not trans_id or not trans_name or not trans_price :
        messagebox.showerror("错误","请填写项目ID/项目名称/项目价格")
        return
    try:
        cursor = self.conn.cursor()
        sql = """
              INSERT INTO trans_set (trans_id, trans_name, trans_price,trans_remark) VALUES (?, ?, ?,?)
             """
        params = ( trans_id,trans_name,trans_price,trans_remark )
        cursor.execute(sql,params)
        self.conn.commit()
        self.add_window.destroy()
        messagebox.showinfo("成功","项目添加成功")
        self.load_trans_items() # 添加成功后刷新项目列表
    except sqlite3.IntegrityError:
        messagebox.showerror("错误","项目添加失败,请检查是否项目ID重复")
def load_trans_items(self):

  """加载项目列表"""
  for row in tree.get_children():
      tree.delete(row)
  cursor = self.conn.cursor()
  cursor.execute(
    "SELECT trans_id, trans_name, trans_price, trans_remark FROM trans_set")
  for trans_item in cursor.fetchall():
      tree.insert('', tk.END, values=trans_item)

# ==========================会员充值相关=================
def show_recharge(self):

    """显示充值窗口"""
    # 获取菜单文本和描述(values 的第一个元素)
    item = self.tree.selection()
    menu_text = self.tree.item(item, "text")
    if menu_text != "会员充值":
        messagebox.showinfo("提示", "请先在左边菜单选择:会员管理->会员充值 才能操作")
        return
    selected = tree.focus()
    if  not selected:
        messagebox.showerror("错误","请先选择会员")
        return
    self.recharge_window = tk.Toplevel(self.root)
    self.recharge_window.title("会员充值")
    ttk.Label(self.recharge_window, text="充值金额:").grid(row=0, column=0, padx=5,pady=5)
    self.amount_entry = ttk.Entry(self.recharge_window)
    self.amount_entry.grid(row=0, column=1)
    ttk.Button(self.recharge_window, text="确认充值", command=self.process_recharge).grid(row=1, columnspan=2,pady=10)
    # 计算居中位置
    self.root.update_idletasks()  # 强制更新窗口几何信息
    parent_x = self.root.winfo_x()
    parent_y = self.root.winfo_y()
    parent_width = self.root.winfo_width()
    parent_height = self.root.winfo_height()
    child_width = 200  # 子窗口固定宽度
    child_height = 200  # 子窗口固定高度

    # 计算子窗口左上角坐标
    x = parent_x + (parent_width - child_width) // 2
    y = parent_y + (parent_height - child_height) // 2

    # 设置子窗口位置
    self.recharge_window.geometry(f"+{x}+{y}")
def process_recharge(self):

    """处理充值操作"""
    try:
        amount =float(self.amount_entry.get())
        if amount <= 0:
            raise ValueError
    except:
        messagebox.showerror("错误","请输入有效的金额")
        return
    selected = tree.focus()
    member_id = tree.item(selected)['values'][0]
    #print(member_id)
    cursor = self.conn.cursor()
    # 更新余额
    cursor.execute("UPDATE members SET balance = balance + ? WHERE id = ?", (amount, member_id))
    # 记录交易
    cursor.execute("INSERT INTO transactions (member_id, amount, type, description, date) VALUES (?, ?, ?, ?, ?)",
                   (member_id, amount,'充值','会员充值', datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
    self.conn.commit()
    self.load_members()
    self.recharge_window.destroy()
    messagebox.showinfo("成功",f"成功充值{amount}元")
# ==========================会员消费相关=================
def show_consume(self):

    """显示消费窗口"""
    # 获取菜单文本和描述(values 的第一个元素)
    item = self.tree.selection()
    menu_text = self.tree.item(item, "text")
    if menu_text != "会员消费":
        messagebox.showinfo("提示", "请先在左边菜单选择:会员管理->会员消费 才能操作")
        return
    selected = tree.focus()
    if  not selected:
        messagebox.showerror("错误","请先选择会员")
        return
    self.consume_window = tk.Toplevel(self.root)
    self.consume_window.title("会员消费")
    # 消费项目选择
    ttk.Label(self.consume_window, text="消费项目:").grid(row=0, column=0, padx=5, pady=5)
    #services = ["剪发","烫发","染发","护理","肩颈","美容","其他"]
    services =[]
    # 连接表查询出数据
    cursor = self.conn.cursor()
    services = []  # 存储 Combobox 展示的名称
    price_dict = {}  # 名称到价格的映射
    # 添加数据
    try:
        cursor.execute("SELECT trans_name, trans_price FROM trans_set")
        rows = cursor.fetchall()
        # 构建名称列表和价格字典
        for row in rows:
            service_name = row
            service_price = row
            services.append(service_name)
            price_dict[service_name] = service_price  # 名称作为键,价格作为值
    finally:
        cursor.close()
    self.service_var = tk.StringVar()
    self.service_menu = ttk.Combobox(self.consume_window, textvariable=self.service_var, values=services)
    self.service_menu.grid(row=0, column=1)
    # 绑定选择事件
    #self.service_menu.bind("<<ComboboxSelected>>", self._update_price)
    ttk.Label(self.consume_window, text="消费金额:").grid(row=1, column=0, padx=5,pady=5)
    self.consume_amount = ttk.Entry(self.consume_window)
    self.consume_amount.grid(row=1, column=1)
    ttk.Button(self.consume_window, text="确认消费", command=self.process_consume).grid(row=2, columnspan=2, pady=10)
    # 计算居中位置
    self.root.update_idletasks()  # 强制更新窗口几何信息
    parent_x = self.root.winfo_x()
    parent_y = self.root.winfo_y()
    parent_width = self.root.winfo_width()
    parent_height = self.root.winfo_height()
    child_width = 200  # 子窗口固定宽度
    child_height = 200  # 子窗口固定高度

    # 计算子窗口左上角坐标
    x = parent_x + (parent_width - child_width) // 2
    y = parent_y + (parent_height - child_height) // 2

    # 设置子窗口位置
    self.consume_window.geometry(f"+{x}+{y}")
def _update_price(self, event):
    "价格更新函数"
    price_dict={}
    selected_service = self.service_var.get()  # 获取选中的服务名称
    price_dict = selected_service
    print(price_dict)
    price = price_dict.get(selected_service, "")

    # 清空并更新消费金额输入框
    self.consume_amount.delete(0, tk.END)
    self.consume_amount.insert(0, price)
def process_consume(self):

    """处理消费操作"""
    try:
        amount = float(self.consume_amount.get())
        if amount <= 0:
            raise ValueError
    except:
        messagebox.showerror("错误","请输入有效的金额")
        return
    selected = tree.focus()
    member_id = tree.item(selected)['values'][0]
    current_balance =float(tree.item(selected)['values'][3])
    if current_balance < amount:
        messagebox.showerror("错误","会员余额不足")
        return
    service_type = self.service_var.get() or "其他"
    cursor = self.conn.cursor()
    try:
        # 更新余额和积分(假设消费1元积1分)
        cursor.execute("UPDATE members SET balance = balance - ?, points = points + ? WHERE id = ?",
                       (amount,int(amount), member_id))
        # 记录消费交易
        cursor.execute('''INSERT INTO transactions  (member_id, amount, type, description, date)  VALUES (?, ?, ?, ?, ?)''',(member_id, amount,'消费',f'{service_type}服务',  datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
        self.conn.commit()
        self.load_members()
        self.consume_window.destroy()
        messagebox.showinfo("成功",f"{service_type}消费{amount}元,剩余积分:{int(amount)}")
    except Exception as e:
        messagebox.showerror("错误",f"操作失败:{str(e)}")

# ==========================交易记录相关=================
def show_transactions(self):

    """显示交易记录窗口"""
    selected = tree.focus()
    if  not selected:
        messagebox.showerror("错误","请先选择会员")
        return
    member_id = tree.item(selected)['values'][0]
    # 创建交易记录窗口
    self.trans_window = tk.Toplevel(self.root)
    self.trans_window.title("交易记录")
    self.trans_window.geometry("600x400")
    # 交易记录表格
    columns = ('日期','类型','金额','描述')
    self.trans_tree = ttk.Treeview(self.trans_window, columns=columns, show='headings')
    # 设置列宽
    col_widths = [150,80,80,200]
    for col, width in zip(columns, col_widths):
        self.trans_tree.heading(col, text=col)
        self.trans_tree.column(col, width=width,anchor="center") # 列居中对齐
    self.trans_tree.pack(side=tk.LEFT,fill=tk.BOTH, expand=True)
    # 加载数据
    self.load_transactions(member_id)
    # 添加滚动条
    scrollbar = ttk.Scrollbar(self.trans_window, orient=tk.VERTICAL, command=self.trans_tree.yview)
    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
    self.trans_tree.configure(yscrollcommand=scrollbar.set)

def load_transactions(self, member_id):

    """加载交易记录"""
    for row in self.trans_tree.get_children():
        self.trans_tree.delete(row)
    cursor = self.conn.cursor()
    cursor.execute(
        '''SELECT date, type, amount, description FROM transactions WHERE member_id = ?  ORDER BY date DESC''',
        (member_id,))
    for trans in cursor.fetchall():
        # 金额显示添加符号
        amount = trans[2]
        display_amount =f"+{amount}" if trans[1] =='充值'else f"-{amount}"
        self.trans_tree.insert('', tk.END, values=(trans[0], trans[1], display_amount, trans[3]))
def show_trans_list(self):

    """加载交易列表"""
    global  tree
    search_entry.bind('<KeyRelease>', self.search_trans)
    columns = ('用户ID','姓名','电话','金额','类型','描述','注册日期')
    tree = ttk.Treeview(self.bottom_right_frame, columns=columns, show="headings")
    # 设置列标题和宽度
    for col in columns:
        tree.heading(col, text=col)
        tree.column(col, width=50,anchor="center")  # 列居中对齐
    # 删除行数据
    for row in tree.get_children():
        tree.delete(row)
    # 连接表查询出数据
    cursor = self.conn.cursor()
    cursor.execute("SELECT distinct member_id, name, phone,amount, type, description, date "
                   "FROM members , transactions where transactions.member_id = members.id ")
    # 添加数据
    for trans in cursor.fetchall():
        member_id, name, phone,amount, type, description,date = trans
        tree.insert('',tk.END,values=(member_id, name, phone,amount, type, description,date))
    tree.pack(side=tk.LEFT,expand=True, fill="both")
    #添加滚动条
    scrollbar = ttk.Scrollbar(self.bottom_right_frame, orient=tk.VERTICAL, command=tree.yview,style="Vertical.TScrollbar")
    tree.configure(yscrollcommand=scrollbar.set)
    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

# ==========================用户管理相关=================
def show_user_management(self):

    """加载用户列表"""
    columns = ('用户ID','姓名','密码','注册日期')
    tree = ttk.Treeview(self.bottom_right_frame, columns=columns, show="headings")
    # 设置列标题和宽度
    for col in columns:
        tree.heading(col, text=col)
        tree.column(col, width=50,anchor="center")  # 列居中对齐
    # 删除行数据
    for row in tree.get_children():
        tree.delete(row)
    # 连接表查询出数据
    cursor = self.conn.cursor()
    cursor.execute("SELECT user_id, user_name, '******' ,reg_date FROM user_mstr")
    # 添加数据
    for users in cursor.fetchall():
        user_id, user_name, user_password, reg_date = users
        tree.insert('',tk.END,values=(user_id,user_name,user_password,reg_date))
        #tree.insert('', tk.END, values=member)
    tree.pack(side=tk.LEFT,expand=True, fill="both")
    #添加滚动条
    scrollbar = ttk.Scrollbar(self.bottom_right_frame, orient=tk.VERTICAL, command=tree.yview,style="Vertical.TScrollbar")
    tree.configure(yscrollcommand=scrollbar.set)
    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

if name == "main":
app = LoginWindow()
app.run()

分类: Python

相关推荐

Python入门学习记录之一:变量_python怎么用变量

写这个,主要是对自己学习python知识的一个总结,也是加深自己的印象。变量(英文:variable),也叫标识符。在python中,变量的命名规则有以下三点:>变量名只能包含字母、数字和下划线...

python变量命名规则——来自小白的总结

python是一个动态编译类编程语言,所以程序在运行前不需要如C语言的先行编译动作,因此也只有在程序运行过程中才能发现程序的问题。基于此,python的变量就有一定的命名规范。python作为当前热门...

Python入门学习教程:第 2 章 变量与数据类型

2.1什么是变量?在编程中,变量就像一个存放数据的容器,它可以存储各种信息,并且这些信息可以被读取和修改。想象一下,变量就如同我们生活中的盒子,你可以把东西放进去,也可以随时拿出来看看,甚至可以换成...

绘制学术论文中的“三线表”具体指导

在科研过程中,大家用到最多的可能就是“三线表”。“三线表”,一般主要由三条横线构成,当然在变量名栏里也可以拆分单元格,出现更多的线。更重要的是,“三线表”也是一种数据记录规范,以“三线表”形式记录的数...

Python基础语法知识--变量和数据类型

学习Python中的变量和数据类型至关重要,因为它们构成了Python编程的基石。以下是帮助您了解Python中的变量和数据类型的分步指南:1.变量:变量在Python中用于存储数据值。它们充...

一文搞懂 Python 中的所有标点符号

反引号`无任何作用。传说Python3中它被移除是因为和单引号字符'太相似。波浪号~(按位取反符号)~被称为取反或补码运算符。它放在我们想要取反的对象前面。如果放在一个整数n...

Python变量类型和运算符_python中变量的含义

别再被小名词坑哭了:Python新手常犯的那些隐蔽错误,我用同事的真实bug拆给你看我记得有一次和同事张姐一起追查一个看似随机崩溃的脚本,最后发现罪魁祸首竟然是她把变量命名成了list。说实话...

从零开始:深入剖析 Spring Boot3 中配置文件的加载顺序

在当今的互联网软件开发领域,SpringBoot无疑是最为热门和广泛应用的框架之一。它以其强大的功能、便捷的开发体验,极大地提升了开发效率,成为众多开发者构建Web应用程序的首选。而在Spr...

Python中下划线 ‘_’ 的用法,你知道几种

Python中下划线()是一个有特殊含义和用途的符号,它可以用来表示以下几种情况:1在解释器中,下划线(_)表示上一个表达式的值,可以用来进行快速计算或测试。例如:>>>2+...

解锁Shell编程:变量_shell $变量

引言:开启Shell编程大门Shell作为用户与Linux内核之间的桥梁,为我们提供了强大的命令行交互方式。它不仅能执行简单的文件操作、进程管理,还能通过编写脚本实现复杂的自动化任务。无论是...

一文学会Python的变量命名规则!_python的变量命名有哪些要求

目录1.变量的命名原则3.内置函数尽量不要做变量4.删除变量和垃圾回收机制5.结语1.变量的命名原则①由英文字母、_(下划线)、或中文开头②变量名称只能由英文字母、数字、下画线或中文字所组成。③英文字...

更可靠的Rust-语法篇-区分语句/表达式,略览if/loop/while/for

src/main.rs://函数定义fnadd(a:i32,b:i32)->i32{a+b//末尾表达式}fnmain(){leta:i3...

C++第五课:变量的命名规则_c++中变量的命名规则

变量的命名不是想怎么起就怎么起的,而是有一套固定的规则的。具体规则:1.名字要合法:变量名必须是由字母、数字或下划线组成。例如:a,a1,a_1。2.开头不能是数字。例如:可以a1,但不能起1a。3....

Rust编程-核心篇-不安全编程_rust安全性

Unsafe的必要性Rust的所有权系统和类型系统为我们提供了强大的安全保障,但在某些情况下,我们需要突破这些限制来:与C代码交互实现底层系统编程优化性能关键代码实现某些编译器无法验证的安全操作Rus...

探秘 Python 内存管理:背后的神奇机制

在编程的世界里,内存管理就如同幕后的精密操控者,确保程序的高效运行。Python作为一种广泛使用的编程语言,其内存管理机制既巧妙又复杂,为开发者们提供了便利的同时,也展现了强大的底层控制能力。一、P...