如何使用函数在 Tkinter GUI 中拥有多个页面(无需打开新窗口)?

Shw*_*Raj 4 tkinter

我想创建一个 GUI,其中有几个页面,当单击它们各自的按钮时,我想在同一窗口中打开这些页面。有一种使用我遇到的类的解决方案:Using Buttons in Tkinter to navigation to different Pages of the application? 然而,我是 Tkinter 的新手,到目前为止我实现的 GUI 一直使用函数而不是类。有人可以解释如何使用函数来做到这一点吗?

May*_*yan 7

我想这就是你想要的。请下次尝试包含一些代码,以便其他人可以更直接地提供帮助。这个想法是销毁所有小部件,然后在按下按钮时构建另一个页面。.winfo_children() 返回“root”的所有子节点

import tkinter as tk

def page1(root):
    page = tk.Frame(root)
    page.grid()
    tk.Label(page, text = 'This is page 1').grid(row = 0)
    tk.Button(page, text = 'To page 2', command = changepage).grid(row = 1)

def page2(root):
    page = tk.Frame(root)
    page.grid()
    tk.Label(page, text = 'This is page 2').grid(row = 0)
    tk.Button(page, text = 'To page 1', command = changepage).grid(row = 1)

def changepage():
    global pagenum, root
    for widget in root.winfo_children():
        widget.destroy()
    if pagenum == 1:
        page2(root)
        pagenum = 2
    else:
        page1(root)
        pagenum = 1

pagenum = 1
root = tk.Tk()
page1(root)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)

我知道当我们第一次学习编程时,对象和类有点笨拙。但当你习惯了它们后,它们会非常有用。