【问题标题】:Remove all widgets after clicking button?单击按钮后删除所有小部件?
【发布时间】:2018-08-27 10:36:02
【问题描述】:

我正在使用 tkinter 创建登录/注册系统。当用户单击登录或注册时,我希望所有小部件都消失,以便新的小部件出现在屏幕上,具体取决于他们是否单击了登录或注册。因此,如果他们单击登录,则会出现新的标签和文本框,以显示他们的用户名和密码。问题是我正在使用 .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()

我的界面:

【问题讨论】:

  • 你试过place_forget吗?
  • fhdrsdg 哦,这很好用
  • 你也可以destroy()这个小部件。

标签: python python-3.x tkinter tkinter-layout


【解决方案1】:

无论您使用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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 2020-11-02
    • 2023-01-22
    • 1970-01-01
    • 2022-11-21
    相关资源
    最近更新 更多