Python创建可视化页面并实现页面跳转

import tkinter as tk

class Page1(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        # 添加页面1的内容
        label = tk.Label(self, text="这是页面1")
        label.pack(pady=10)

        # 添加换页按钮
        button = tk.Button(self, text=">>", command=self.change_to_page2)
        button.pack(side="right", padx=10, pady=10, anchor="se")

    def change_to_page2(self):
        self.controller.show_frame(Page2)


class Page2(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller

        # 添加页面2的内容
        label = tk.Label(self, text="这是页面2")
        label.pack(pady=10)

        # 添加换页按钮
        button = tk.Button(self, text="<<", command=self.change_to_page1)
        button.pack(side="right", padx=10, pady=10, anchor="sw")

    def change_to_page1(self):
        self.controller.show_frame(Page1)

class MyApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        # 设置主窗口的属性
        self.title("页面切换示例")
        self.geometry("400x200")

        # 创建一个容器来存放页面
        container = tk.Frame(self)
        container.pack(fill="both", expand=True)

        # 创建一个字典来存放不同页面的实例
        self.frames = {}

        # 添加Page1和Page2到字典中
        for Page in (Page1, Page2):
            frame = Page(container, self)
            self.frames[Page] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        # 默认显示第一个页面
        self.show_frame(Page1)

    def show_frame(self, page):
        frame = self.frames[page]
        frame.tkraise()

if __name__ == "__main__":
    app = MyApp()
    app.mainloop()

你可能感兴趣的:(python,开发语言)