tkinter库删除第一个页面同时跳转到第二个页面
时间: 2023-08-04 13:05:03 浏览: 139
下面是一个示例代码,展示如何使用tkinter库删除第一个页面并同时跳转到第二个页面:
```python
import tkinter as tk
class PageOne(tk.Frame):
def __init__(self, master, mainapp):
tk.Frame.__init__(self, master)
self.mainapp = mainapp
tk.Label(self, text="This is Page One").pack()
tk.Button(self, text="Go to Page Two", command=lambda: self.switch_to_page_two()).pack()
def switch_to_page_two(self):
self.mainapp.show_frame(PageTwo)
self.mainapp.destroy_frame(PageOne)
class PageTwo(tk.Frame):
def __init__(self, master, mainapp):
tk.Frame.__init__(self, master)
self.mainapp = mainapp
tk.Label(self, text="This is Page Two").pack()
tk.Button(self, text="Go to Page One", command=lambda: self.switch_to_page_one()).pack()
def switch_to_page_one(self):
self.mainapp.show_frame(PageOne)
self.mainapp.destroy_frame(PageTwo)
class MainApplication(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("Page Navigation")
self.geometry("300x200")
container = tk.Frame(self)
container.pack(side="top", fill="both", expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
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, frame_class):
frame = self.frames[frame_class]
frame.tkraise()
def destroy_frame(self, frame_class):
frame = self.frames[frame_class]
frame.destroy()
del self.frames[frame_class]
if __name__ == "__main__":
app = MainApplication()
app.mainloop()
```
在这个例子中,我们添加了一个destroy_frame方法,用于删除页面。每个页面类的构造函数都传入了主应用程序实例。在PageOne类中,我们重写了switch_to_page_two方法,它首先调用show_frame方法来切换到PageTwo页面,然后调用destroy_frame方法来删除PageOne页面。在PageTwo类中,我们同样重写了switch_to_page_one方法,它首先调用show_frame方法来切换到PageOne页面,然后调用destroy_frame方法来删除PageTwo页面。在MainApplication类中,我们添加了destroy_frame方法来删除页面。它接受一个页面类作为参数,通过该类从我们之前创建的frames字典中获取要删除的页面实例。然后我们调用destroy方法来销毁该页面,并从frames字典中删除该页面实例。
阅读全文