在tkinter GUI应用程序中创建多个页面可以通过以下步骤实现:
import tkinter as tk
root = tk.Tk()
class Page(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
class Page(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="This is Page 1")
label.pack()
button = tk.Button(self, text="Go to Page 2", command=self.goto_page2)
button.pack()
def goto_page2(self):
# 切换到第二个页面
root.show_page(Page2)
root = tk.Tk()
# 创建页面对象
page1 = Page(root)
page2 = Page(root)
# 将页面对象添加到主窗口中
page1.pack()
class Page(tk.Frame):
def goto_page2(self):
# 切换到第二个页面
root.show_page(Page2)
def show_page(self, page):
page.pack()
完整的示例代码如下:
import tkinter as tk
class Page(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="This is Page 1")
label.pack()
button = tk.Button(self, text="Go to Page 2", command=self.goto_page2)
button.pack()
def goto_page2(self):
root.show_page(Page2)
class Page2(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="This is Page 2")
label.pack()
button = tk.Button(self, text="Go to Page 1", command=self.goto_page1)
button.pack()
def goto_page1(self):
root.show_page(Page)
class MainApplication(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# 创建页面对象
page1 = Page(self)
page2 = Page2(self)
# 将页面对象添加到主窗口中
page1.pack()
self.pages = [page1, page2]
def show_page(self, page):
for p in self.pages:
p.pack_forget()
page.pack()
if __name__ == "__main__":
root = MainApplication()
root.mainloop()
这样,你就可以在tkinter GUI应用程序中创建多个页面,并通过按钮等组件在页面之间进行切换。
领取专属 10元无门槛券
手把手带您无忧上云