import tkinter as tk
from tkinter import colorchooser, messagebox, filedialog
from PIL import Image, ImageDraw
import os


class DrawingBoard:
    def __init__(self, root):
        self.root = root
        self.root.title("🎨 简易画图板")
        self.root.geometry("800x550")
        self.root.resizable(False, False)

        # ===== 状态变量 =====
        self.current_color = "#000000"   # 默认黑色
        self.pen_width = 3               # 默认画笔粗细
        self.eraser_width = 20           # 橡皮擦大小
        self.is_eraser = False           # 是否橡皮擦模式
        self.drawing = False
        self.last_x = None
        self.last_y = None

        # 画布图像（用于保存）
        self.canvas_width = 800
        self.canvas_height = 470
        self.image = Image.new("RGB", (self.canvas_width, self.canvas_height), "white")
        self.draw = ImageDraw.Draw(self.image)

        self.setup_ui()

    def setup_ui(self):
        # ===== 顶部工具栏 =====
        toolbar = tk.Frame(self.root, bg="#f0f0f0", height=50)
        toolbar.pack(fill=tk.X)
        toolbar.pack_propagate(False)

        # 画笔按钮
        self.pen_btn = tk.Button(
            toolbar, text="✏️ 画笔", width=8,
            font=("Microsoft YaHei", 10),
            bg="#4CAF50", fg="white", activebackground="#45a049",
            command=self.use_pen
        )
        self.pen_btn.pack(side=tk.LEFT, padx=5, pady=8)

        # 橡皮擦按钮
        self.eraser_btn = tk.Button(
            toolbar, text="🧽 橡皮擦", width=8,
            font=("Microsoft YaHei", 10),
            bg="#9E9E9E", fg="white", activebackground="#757575",
            command=self.use_eraser
        )
        self.eraser_btn.pack(side=tk.LEFT, padx=5, pady=8)

        # 颜色选择
        tk.Button(
            toolbar, text="🎨 颜色", width=8,
            font=("Microsoft YaHei", 10),
            command=self.choose_color
        ).pack(side=tk.LEFT, padx=5, pady=8)

        # 颜色预览
        self.color_preview = tk.Label(
            toolbar, bg=self.current_color, width=3, relief=tk.RIDGE, bd=2
        )
        self.color_preview.pack(side=tk.LEFT, padx=2, pady=8)

        # 画笔粗细
        tk.Label(toolbar, text="粗细：", font=("Microsoft YaHei", 9)).pack(side=tk.LEFT, padx=(15, 2), pady=8)
        self.width_scale = tk.Scale(
            toolbar, from_=1, to=20, orient=tk.HORIZONTAL,
            variable=tk.IntVar(value=self.pen_width),
            command=self.change_pen_width, length=100
        )
        self.width_scale.pack(side=tk.LEFT, padx=2, pady=8)

        # 清空按钮
        tk.Button(
            toolbar, text="🗑 清空", width=8,
            font=("Microsoft YaHei", 10),
            bg="#f44336", fg="white", activebackground="#da190b",
            command=self.clear_canvas
        ).pack(side=tk.LEFT, padx=5, pady=8)

        # 保存按钮
        tk.Button(
            toolbar, text="💾 保存", width=8,
            font=("Microsoft YaHei", 10),
            bg="#2196F3", fg="white", activebackground="#1976D2",
            command=self.save_image
        ).pack(side=tk.LEFT, padx=5, pady=8)

        # ===== 画布 =====
        self.canvas = tk.Canvas(
            self.root, bg="white",
            width=self.canvas_width, height=self.canvas_height,
            cursor="pencil"
        )
        self.canvas.pack()

        # 绑定鼠标事件
        self.canvas.bind("<Button-1>", self.start_draw)
        self.canvas.bind("<B1-Motion>", self.draw_line)
        self.canvas.bind("<ButtonRelease-1>", self.stop_draw)

        # 底部提示
        self.status_label = tk.Label(
            self.root, text="✏️ 画笔模式  |  左键拖动绘图",
            font=("Microsoft YaHei", 9), fg="#666",
            anchor=tk.W
        )
        self.status_label.pack(fill=tk.X, padx=10, pady=3)

    # ===== 核心绘图逻辑 =====
    def start_draw(self, event):
        self.drawing = True
        self.last_x = event.x
        self.last_y = event.y

    def draw_line(self, event):
        if not self.drawing:
            return

        x, y = event.x, event.y

        if self.is_eraser:
            # 橡皮擦：画白色
            fill_color = "white"
            width = self.eraser_width
        else:
            fill_color = self.current_color
            width = self.pen_width

        # 在 tkinter 画布上画
        self.canvas.create_line(
            self.last_x, self.last_y, x, y,
            fill=fill_color, width=width,
            capstyle=tk.ROUND, smooth=True
        )

        # 在 PIL 图像上画（用于保存）
        pil_color = fill_color
        self.draw.line(
            [self.last_x, self.last_y, x, y],
            fill=pil_color, width=width
        )

        self.last_x = x
        self.last_y = y

    def stop_draw(self, event):
        self.drawing = False
        self.last_x = None
        self.last_y = None

    # ===== 工具栏功能 =====
    def use_pen(self):
        self.is_eraser = False
        self.pen_btn.config(bg="#4CAF50", fg="white")
        self.eraser_btn.config(bg="#9E9E9E", fg="white")
        self.status_label.config(text="✏️ 画笔模式  |  左键拖动绘图")
        self.canvas.config(cursor="pencil")

    def use_eraser(self):
        self.is_eraser = True
        self.eraser_btn.config(bg="#f44336", fg="white")
        self.pen_btn.config(bg="#9E9E9E", fg="white")
        self.status_label.config(text="🧽 橡皮擦模式  |  左键拖动擦除")
        self.canvas.config(cursor="dotbox")

    def choose_color(self):
        color = colorchooser.askcolor(title="选择画笔颜色")
        if color and color[1]:
            self.current_color = color[1]
            self.color_preview.config(bg=self.current_color)
            # 切回画笔模式
            self.use_pen()

    def change_pen_width(self, value):
        if self.is_eraser:
            self.eraser_width = int(value)
        else:
            self.pen_width = int(value)

    def clear_canvas(self):
        if messagebox.askyesno("确认", "确定要清空画布吗？"):
            self.canvas.delete("all")
            self.image = Image.new("RGB", (self.canvas_width, self.canvas_height), "white")
            self.draw = ImageDraw.Draw(self.image)

    def save_image(self):
        filename = filedialog.asksaveasfilename(
            title="保存图片",
            defaultextension=".png",
            filetypes=[("PNG 图片", "*.png"), ("JPEG 图片", "*.jpg"), ("所有文件", "*.*")]
        )
        if filename:
            try:
                self.image.save(filename)
                messagebox.showinfo("成功", f"图片已保存到：\n{filename}")
            except Exception as e:
                messagebox.showerror("错误", f"保存失败：{e}")


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