# 唐诗三百首GUI阅读器 防无窗口崩溃版
try:
    import tkinter as tk
    from tkinter import ttk, scrolledtext, messagebox
except ImportError:
    print("错误：你的Python缺少tkinter组件")
    print("Windows重装Python，安装时勾选tcl/tk and IDLE")
    print("Mac终端：brew install python-tk")
    print("Ubuntu：sudo apt install python3-tk")
    input("按回车退出")
    exit()

poem_list = [
    {"title": "静夜思", "author": "李白", "content": "床前明月光，疑是地上霜。\n举头望明月，低头思故乡。"},
    {"title": "春晓", "author": "孟浩然", "content": "春眠不觉晓，处处闻啼鸟。\n夜来风雨声，花落知多少。"},
    {"title": "登鹳雀楼", "author": "王之涣", "content": "白日依山尽，黄河入海流。\n欲穷千里目，更上一层楼。"},
    {"title": "相思", "author": "王维", "content": "红豆生南国，春来发几枝。\n愿君多采撷，此物最相思。"},
    {"title": "咏鹅", "author": "骆宾王", "content": "鹅，鹅，鹅，曲项向天歌。\n白毛浮绿水，红掌拨清波。"}
]

root = tk.Tk()
root.title("唐诗三百首")
root.geometry("850x550")
root.resizable(True, True)

# 顶部搜索
frame_top = tk.Frame(root)
frame_top.pack(fill="x", padx=10, pady=5)
tk.Label(frame_top, text="搜索:").pack(side="left")
entry_search = tk.Entry(frame_top, width=30)
entry_search.pack(side="left", padx=4)

def search():
    kw = entry_search.get().strip()
    if not kw:
        messagebox.showinfo("提示", "请输入关键词")
        return
    for idx, p in enumerate(poem_list):
        if kw in p["title"] or kw in p["author"] or kw in p["content"]:
            show(idx)
            return
    messagebox.showerror("结果", "未找到该诗词")

tk.Button(frame_top, text="搜索", command=search).pack(side="left", padx=3)

# 左右分割
paned = ttk.PanedWindow(root, orient=tk.HORIZONTAL)
paned.pack(fill="both", expand=True, padx=10, pady=5)

# 左侧列表框
frame_left = ttk.Frame(paned, width=220)
paned.add(frame_left, weight=1)
tk.Label(frame_left, text="诗词目录", font=("SimHei",11,"bold")).pack()
listbox = tk.Listbox(frame_left, font=("SimHei",10))
scroll_left = ttk.Scrollbar(frame_left, command=listbox.yview)
listbox.config(yscrollcommand=scroll_left.set)
scroll_left.pack(side="right", fill="y")
listbox.pack(fill="both", expand=True)

# 右侧内容
frame_right = ttk.Frame(paned)
paned.add(frame_right, weight=3)
lab_title = tk.Label(frame_right, font=("SimHei",16,"bold"), anchor="w")
lab_title.pack(anchor="w", padx=5)
lab_author = tk.Label(frame_right, font=("SimHei",11), anchor="w")
lab_author.pack(anchor="w", padx=5)
txt_content = scrolledtext.ScrolledText(frame_right, font=("SimHei",14))
txt_content.pack(fill="both", expand=True, pady=6)
txt_content.config(state="disabled")

# 底部按钮
frame_bottom = tk.Frame(root)
frame_bottom.pack(pady=6)
idx_now = 0

def show(index):
    global idx_now
    if 0 <= index < len(poem_list):
        idx_now = index
        p = poem_list[index]
        lab_title.config(text=p["title"])
        lab_author.config(text="作者：" + p["author"])
        txt_content.config(state="normal")
        txt_content.delete(1.0, tk.END)
        txt_content.insert(tk.END, p["content"])
        txt_content.config(state="disabled")
        listbox.selection_clear(0, tk.END)
        listbox.selection_set(index)

def prev_one():
    show(idx_now - 1)

def next_one():
    show(idx_now + 1)

tk.Button(frame_bottom, text="上一首", command=prev_one, width=8).grid(row=0,column=0,padx=8)
tk.Button(frame_bottom, text="下一首", command=next_one, width=8).grid(row=0,column=1,padx=8)

# 填充列表
for item in poem_list:
    listbox.insert(tk.END, item["title"])

def click_list(event):
    sel = listbox.curselection()
    if sel:
        show(sel[0])

listbox.bind("<<ListboxSelect>>", click_list)

# 初始显示第一首
show(0)

# 必须开启主循环，这是弹出窗口核心
if __name__ == "__main__":
    try:
        root.mainloop()
    except Exception as err:
        print("程序异常:", err)
        input("\n程序无法启动，按回车关闭窗口")