6.6打卡

python大作业管理员页面
• 所花时间:5
• 代码行数:145
• 博客容量:1
• 代码如下:

import pandas as pd
from tkinter import filedialog
import mysql.connector
import tkinter as tk
from tkinter import messagebox

# 假设 database.py 中已经有 connect_db 函数
import database as db


def center_window(window, width=400, height=300):
    screen_width = window.winfo_screenwidth()
    screen_height = window.winfo_screenheight()
    x = (screen_width / 2) - (width / 2)
    y = (screen_height / 2) - (height / 2)
    window.geometry(f'{width}x{height}+{int(x)}+{int(y)}')

def show_admin_main_page(username):
    main_page = tk.Tk()
    main_page.title("管理员主页面")
    main_page.geometry("1000x600")
    center_window(main_page, 1000, 600)

    admin_label = tk.Label(main_page, text=f"欢迎管理员: {username}", font=('Arial', 18))
    admin_label.pack(pady=20)

    create_dormitory_button = tk.Button(main_page, text="创建宿舍楼",
                                        command=lambda: create_dormitory(username, main_page), width=20, height=2,
                                        bg='#0F6DF0', fg='white', borderwidth=0, relief="flat")
    create_dormitory_button.pack(pady=10)

    handle_maintenance_button = tk.Button(main_page, text="处理报修请求",
                                          command=lambda: handle_maintenance_requests(username, main_page), width=20,
                                          height=2, bg='#0F6DF0', fg='white', borderwidth=0, relief="flat")
    handle_maintenance_button.pack(pady=10)

    handle_swap_requests_button = tk.Button(main_page, text="查看调换宿舍请求",
                                            command=lambda: handle_swap_requests(username, main_page), width=20, height=2,
                                            bg='#0F6DF0', fg='white', borderwidth=0, relief="flat")
    handle_swap_requests_button.pack(pady=10)

    import_students_button = tk.Button(main_page, text="导入学生数据",
                                       command=lambda: import_students(username, main_page), width=20, height=2,
                                       bg='#0F6DF0', fg='white', borderwidth=0, relief="flat")
    import_students_button.pack(pady=10)

    main_page.mainloop()

def import_students(username, main_page):
    file_path = filedialog.askopenfilename(filetypes=[("Excel files", "*.xlsx")])
    if file_path:
        import_students_from_excel(file_path,main_page)


def create_dormitory(username, main_page):
    clear_window(main_page)
    main_page.title("创建宿舍楼")

    main_page_button = tk.Button(main_page, text="回到主页面", command=lambda: show_admin_main_page(username),
                                 bg='#0F6DF0', fg='white', borderwidth=0, relief="flat", padx=10, pady=5)
    main_page_button.place(relx=0.9, rely=0.02)

    name_label = tk.Label(main_page, text="宿舍楼名称:")
    name_label.place(relx=0.3, rely=0.2, anchor=tk.E)
    name_entry = tk.Entry(main_page, relief="flat")
    name_entry.place(relx=0.6, rely=0.2, anchor=tk.CENTER)

    floors_label = tk.Label(main_page, text="楼层数量:")
    floors_label.place(relx=0.3, rely=0.3, anchor=tk.E)
    floors_entry = tk.Entry(main_page, relief="flat")
    floors_entry.place(relx=0.6, rely=0.3, anchor=tk.CENTER)

    rooms_per_floor_label = tk.Label(main_page, text="每层房间数量:")
    rooms_per_floor_label.place(relx=0.3, rely=0.4, anchor=tk.E)
    rooms_per_floor_entry = tk.Entry(main_page, relief="flat")
    rooms_per_floor_entry.place(relx=0.6, rely=0.4, anchor=tk.CENTER)

    gender_label = tk.Label(main_page, text="宿舍楼性别:")
    gender_label.place(relx=0.3, rely=0.5, anchor=tk.E)
    gender_entry = tk.Entry(main_page, relief="flat")
    gender_entry.place(relx=0.6, rely=0.5, anchor=tk.CENTER)

    def save_dormitory():
        name = name_entry.get()
        floors = floors_entry.get()
        rooms_per_floor = rooms_per_floor_entry.get()
        gender = gender_entry.get()
        db.insert_dormitory(name, floors, rooms_per_floor, gender)
        messagebox.showinfo("成功", "宿舍楼创建成功", parent=main_page)

    save_button = tk.Button(main_page, text="保存", command=save_dormitory, bg='#0F6DF0', fg='white', borderwidth=0,
                            relief="flat", padx=10, pady=5)
    save_button.place(relx=0.5, rely=0.6, anchor=tk.CENTER)

def import_students_from_excel(file_path,main_page):
    df = pd.read_excel(file_path)

    # 处理缺失数据,用默认值替换 NaNs 或跳过包含 NaNs 的行
    df.fillna({
        '学号': '',
        '姓名': '',
        '密码': '',
        '宿舍楼编号': 0,
        '宿舍号': 0,
        '性别': '',
        '职位': ''
    }, inplace=True)

    # 过滤掉关键字段缺失的行
    df = df[df['学号'] != '']
    df = df[df['密码'] != '']

    conn = db.connect_db()
    cursor = conn.cursor()

    for index, row in df.iterrows():
        try:
            cursor.execute("""
                INSERT INTO users (username, name, password, dormitory_id, room_number, gender, role, position)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
            """, (
                row['学号'],
                row['姓名'],
                row['密码'],
                int(row['宿舍楼编号']) if pd.notna(row['宿舍楼编号']) else None,
                int(row['宿舍号']) if pd.notna(row['宿舍号']) else None,
                row['性别'] if row['性别'] in ['男', '女'] else None,
                'student',
                row['职位']
            ))
        except mysql.connector.Error as err:
            print(f"Error: {err}")
            continue  # 如果有错误则跳过这一行

    conn.commit()
    cursor.close()
    conn.close()
    messagebox.showinfo("成功", "学生数据导入成功", parent=main_page)

def handle_maintenance_requests(username, main_page):
    clear_window(main_page)
    main_page.title("处理报修请求")

    main_page_button = tk.Button(main_page, text="回到主页面", command=lambda: show_admin_main_page(username),
                                 bg='#0F6DF0', fg='white', borderwidth=0, relief="flat", padx=10, pady=5)
    main_page_button.pack(pady=5)

    requests = db.get_maintenance_requests()

    for request in requests:
        request_id, reported_by, dormitory_id, room_number, description, handled = request
        request_frame = tk.Frame(main_page, borderwidth=1, relief="solid")
        request_frame.pack(pady=5, padx=10, fill="x")

        request_label = tk.Label(request_frame,
                                 text=f"请求ID: {request_id} | 报修人: {reported_by} | 宿舍楼ID: {dormitory_id} | 房间号: {room_number} | 描述: {description} | 处理状态: {'已处理' if handled else '未处理'}")
        request_label.pack(side="left")

        if not handled:
            handle_button = tk.Button(request_frame, text="标记为已处理", command=lambda rid=request_id: mark_handled(username, main_page, rid),
                                      bg='#0F6DF0', fg='white', borderwidth=0, relief="flat", padx=10, pady=5)
            handle_button.pack(side="right")

def mark_handled(username, main_page, request_id):
    db.update_maintenance_request(request_id)
    messagebox.showinfo("成功", "报修请求已标记为处理", parent=main_page)
    handle_maintenance_requests(username, main_page)

def handle_swap_requests(username, main_page):
    clear_window(main_page)
    main_page.title("查看调换宿舍请求")

    main_page_button = tk.Button(main_page, text="回到主页面", command=lambda: show_admin_main_page(username),
                                 bg='#0F6DF0', fg='white', borderwidth=0, relief="flat", padx=10, pady=5)
    main_page_button.pack(pady=5)

    requests = db.get_room_swap_requests()

    for request in requests:
        request_id, requester_username, partner_username, status = request
        request_frame = tk.Frame(main_page, borderwidth=1, relief="solid")
        request_frame.pack(pady=5, padx=10, fill="x")

        request_label = tk.Label(request_frame,
                                 text=f"请求ID: {request_id} | 申请人: {requester_username} | 同意交换人: {partner_username} | 状态: {status}")
        request_label.pack(side="left")



    main_page.mainloop()


def clear_window(window):
    if not window.winfo_exists():
        return
    for widget in window.winfo_children():
        widget.destroy()

posted @ 2024-06-06 10:56  aallofitisst  阅读(15)  评论(0)    收藏  举报