import tkinter as tk def show_card(card_number): card1_frame.grid_forget() card2_frame.grid_forget() card3_frame.grid_forget() if card_number == 1: card1_frame.grid(row=0, column=0, padx=10, pady=10, sticky="nsew") elif card_number == 2: card2_frame.grid(row=0, column=0, padx=10, pady=10, sticky="nsew") elif card_number == 3: card3_frame.grid(row=0, column=0, padx=10, pady=10, sticky="nsew") root = tk.Tk() root.title("模拟 CardLayout") # 创建一个容器 Frame container = tk.Frame(root) container.pack(fill="both", expand=True) # 创建三个 "卡片" Frame card1_frame = tk.Frame(container, bg="lightblue", padx=50, pady=50) card2_frame = tk.Frame(container, bg="lightgreen", padx=50, pady=50) card3_frame = tk.Frame(container, bg="lightyellow", padx=50, pady=50) card1_label = tk.Label(card1_frame, text="卡片 1") card1_label.pack() card2_label = tk.Label(card2_frame, text="卡片 2") card2_label.pack() card3_label = tk.Label(card3_frame, text="卡片 3") card3_label.pack() # 初始显示第一个卡片 show_card(1) # 创建切换按钮 button1 = tk.Button(root, text="显示卡片 1", command=lambda: show_card(1)) button1.pack(pady=5) button2 = tk.Button(root, text="显示卡片 2", command=lambda: show_card(2)) button2.pack(pady=5) button3 = tk.Button(root, text="显示卡片 3", command=lambda: show_card(3)) button3.pack(pady=5) root.mainloop()