tkinter实现页面切换代码
时间: 2023-10-19 07:07:22 浏览: 58
我可以提供一个基本的例子:
```
import tkinter as tk
class PageOne(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Page One", font=("Helvetica", 18))
label.pack(pady=10, padx=10)
button1 = tk.Button(self, text="Go to page two", command=lambda: controller.show_frame(PageTwo))
button1.pack()
class PageTwo(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
label = tk.Label(self, text="Page Two", font=("Helvetica", 18))
label.pack(pady=10, padx=10)
button1 = tk.Button(self, text="Go to page one", command=lambda: controller.show_frame(PageOne))
button1.pack()
class MainApplication(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
self.frames = {}
for F in (PageOne, PageTwo):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="nsew")
self.show_frame(PageOne)
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
app = MainApplication()
app.mainloop()
```
这段代码使用 `tk.Frame` 和 `tk.Button` 创建了两个页面,并使用 `show_frame` 方法实现页面之间的切换。在每个页面中, `tk.Button` 绑定了一个指向 `show_frame()` 方法的回调函数,该函数将页面切换到另一个页面。注意到 `Show_frame` 函数中使用 `tkraise()` 方法来显示目标框架,该方法可以用于Tkinter的frame子类。在主窗口中,使用一个字典来存储所有的页面,并在构造函数中展示了第一个页面。