单击按钮后删除所有小部件?

Remove all widgets after clicking button?

我正在使用 tkinter 创建一个 login/sign-up 系统。当用户单击登录或注册时,我希望所有小部件都消失,以便新的小部件出现在屏幕上,具体取决于他们是单击登录还是注册。因此,如果他们点击登录,则会出现新的标签和文本框,用于显示他们的用户名和密码。问题是我正在使用 .place() 并且我看到的教程大多使用 pack_forgetgrid_forget

我的代码:

from tkinter import *


class Window:

    def __init__(self, master):

        root.title("Sign Up or Login")
        root.minsize(width=300, height=300)
        root.maxsize(width=300,height=300)

        self.login_button = Button(master, text = "Login", width=18,height=4, command=self.LoginPage)
        self.signup_button = Button(master, text = "Sign Up", width=18,height=4, command=self.SignupPage)

        self.login_button.place(relx=0.5, rely=0.3, anchor=CENTER)
        self.signup_button.place(relx=0.5, rely=0.7, anchor=CENTER)

    def LoginPage(self):
        root.title("Login")

    def SignupPage(self):
        root.title("Sign Up")



root = Tk()

run = Window(root)

root.mainloop()

我的界面:

无论您使用placepack还是grid。适合所有人的最佳解决方案:

for widgets in root.winfo_children():
    widgets.destory()

它循环遍历小部件并删除它们。你可以试试:

from tkinter import *


class Window:

    def __init__(self, master):

        root.title("Sign Up or Login")
        root.minsize(width=300, height=300)
        root.maxsize(width=300,height=300)

        self.login_button = Button(master, text = "Login", width=18,height=4, command=self.LoginPage)
        self.signup_button = Button(master, text = "Sign Up", width=18,height=4, command=self.SignupPage)

        self.login_button.place(relx=0.5, rely=0.3, anchor=CENTER)
        self.signup_button.place(relx=0.5, rely=0.7, anchor=CENTER)

    def LoginPage(self):
        root.title("Login")
        self.Restore()
    def SignupPage(self):
        root.title("Sign Up")
        self.Restore()
    def Restore(self):
            for widgets in root.winfo_children():
                widgets.destroy()


root = Tk()

run = Window(root)

root.mainloop()