编辑代码

import tkinter as tk
from tkinter import ttk, messagebox
from tkcalendar import DateEntry, Calendar
import json
from datetime import date, timedelta

class BookingSystem:
    def __init__(self, master):
        self.master = master
        self.master.title("设备预约系统")

        # 初始化数据结构
        self.bookings = []
        self.load_data()

        # 创建界面组件
        self.create_widgets()
        self.update_display()

    def create_widgets(self):
        # 输入区域
        input_frame = ttk.LabelFrame(self.master, text="新建预约")
        input_frame.pack(padx=10, pady=5, fill=tk.X)

        ttk.Label(input_frame, text="姓名:").grid(row=0, column=0, padx=5, pady=2)
        self.name_entry = ttk.Entry(input_frame)
        self.name_entry.grid(row=0, column=1, padx=5, pady=2)

        ttk.Label(input_frame, text="开始日期:").grid(row=1, column=0, padx=5, pady=2)
        self.start_date = DateEntry(input_frame, date_pattern='y-mm-dd')
        self.start_date.grid(row=1, column=1, padx=5, pady=2)

        ttk.Label(input_frame, text="结束日期:").grid(row=2, column=0, padx=5, pady=2)
        self.end_date = DateEntry(input_frame, date_pattern='y-mm-dd')
        self.end_date.grid(row=2, column=1, padx=5, pady=2)

        ttk.Button(input_frame, text="提交预约", command=self.submit_booking).grid(row=3, columnspan=2, pady=5)

        # 预约列表
        list_frame = ttk.LabelFrame(self.master, text="已存在的预约")
        list_frame.pack(padx=10, pady=5, fill=tk.BOTH, expand=True)

        columns = ('name', 'start', 'end')
        self.booking_tree = ttk.Treeview(list_frame, columns=columns, show='headings')
        self.booking_tree.heading('name', text='姓名')
        self.booking_tree.heading('start', text='开始日期')
        self.booking_tree.heading('end', text='结束日期')
        self.booking_tree.pack(fill=tk.BOTH, expand=True)

        # 日历显示
        cal_frame = ttk.LabelFrame(self.master, text="日历视图")
        cal_frame.pack(padx=10, pady=5, fill=tk.BOTH, expand=True)

        self.calendar = Calendar(cal_frame, selectmode='none')
        self.calendar.pack(fill=tk.BOTH, expand=True)

    def load_data(self):
        try:
            with open('bookings.json', 'r') as f:
                data = json.load(f)
                self.bookings = [{
                    'name': item['name'],
                    'start': date.fromisoformat(item['start']),
                    'end': date.fromisoformat(item['end'])
                } for item in data]
        except FileNotFoundError:
            self.bookings = []

    def save_data(self):
        data = [{
            'name': b['name'],
            'start': b['start'].isoformat(),
            'end': b['end'].isoformat()
        } for b in self.bookings]
        with open('bookings.json', 'w') as f:
            json.dump(data, f)

    def update_display(self):
        # 更新预约列表
        for item in self.booking_tree.get_children():
            self.booking_tree.delete(item)
        for booking in self.bookings:
            self.booking_tree.insert('', 'end', values=(
                booking['name'],
                booking['start'].strftime('%Y-%m-%d'),
                booking['end'].strftime('%Y-%m-%d')
            ))

        # 更新日历标记
        self.calendar.calevent_remove('all')
        for booking in self.bookings:
            current_date = booking['start']
            while current_date <= booking['end']:
                self.calendar.calevent_create(current_date, '已预约', 'reserved')
                current_date += timedelta(days=1)
        self.calendar.tag_config('reserved', background='red', foreground='white')

    def validate_booking(self, new_start, new_end):
        for booking in self.bookings:
            if (new_start <= booking['end'] and new_end >= booking['start']):
                return False
        return True

    def submit_booking(self):
        name = self.name_entry.get().strip()
        start = self.start_date.get_date()
        end = self.end_date.get_date()

        if not name:
            messagebox.showerror("错误", "请输入姓名")
            return
        if start > end:
            messagebox.showerror("错误", "结束日期不能早于开始日期")
            return
        if not self.validate_booking(start, end):
            messagebox.showerror("错误", "时间段与其他预约冲突")
            return

        self.bookings.append({
            'name': name,
            'start': start,
            'end': end
        })
        self.save_data()
        self.update_display()
        messagebox.showinfo("成功", "预约成功!")
        self.name_entry.delete(0, 'end')

if __name__ == "__main__":
    root = tk.Tk()
    app = BookingSystem(root)
    root.mainloop()