tkinter页面切换
时间: 2023-05-29 21:04:49 浏览: 262
在tkinter中实现页面切换可以使用两种方式:
1. 使用多个Frame组件
在主窗口中创建多个Frame组件,每个Frame组件代表一个页面。通过控制每个Frame组件的显示和隐藏来实现页面切换。
示例代码:
```python
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
# 创建多个Frame组件
self.frame1 = tk.Frame(self)
self.frame2 = tk.Frame(self)
# 在Frame组件中添加控件
tk.Label(self.frame1, text='This is frame1').pack()
tk.Button(self.frame1, text='Go to frame2', command=self.show_frame2).pack()
tk.Label(self.frame2, text='This is frame2').pack()
tk.Button(self.frame2, text='Go to frame1', command=self.show_frame1).pack()
# 默认显示第一个Frame组件
self.frame1.pack()
def show_frame1(self):
self.frame2.pack_forget() # 隐藏frame2
self.frame1.pack() # 显示frame1
def show_frame2(self):
self.frame1.pack_forget() # 隐藏frame1
self.frame2.pack() # 显示frame2
if __name__ == '__main__':
app = App()
app.mainloop()
```
2. 使用Notebook组件
Notebook组件是一个带有选项卡的容器,可以在选项卡之间切换显示不同的内容。
示例代码:
```python
import tkinter as tk
from tkinter import ttk
class App(tk.Tk):
def __init__(self):
super().__init__()
# 创建Notebook组件
self.notebook = ttk.Notebook(self)
# 在Notebook组件中添加选项卡
self.frame1 = tk.Frame(self.notebook)
self.notebook.add(self.frame1, text='Page 1')
self.frame2 = tk.Frame(self.notebook)
self.notebook.add(self.frame2, text='Page 2')
# 在选项卡中添加控件
tk.Label(self.frame1, text='This is page 1').pack()
tk.Button(self.frame1, text='Go to page 2', command=self.show_page2).pack()
tk.Label(self.frame2, text='This is page 2').pack()
tk.Button(self.frame2, text='Go to page 1', command=self.show_page1).pack()
# 显示Notebook组件
self.notebook.pack()
def show_page1(self):
self.notebook.select(self.frame1)
def show_page2(self):
self.notebook.select(self.frame2)
if __name__ == '__main__':
app = App()
app.mainloop()
```
以上两种方法都可以实现页面切换,根据实际需求选择适合的方法即可。