Python: 单击时删除按钮并在再次单击时恢复?

Python: Remove a button on click and restore in another click?

我用 Tkinter 写了一个 gui 程序。

 from Tkinter import *     

class Test(object):
    def __init__(self):
        self.root=Tk()
        self.root.resizable(0,0)
        self.lframe = Frame(self.root,width=300,height=200,bg="White",padx=0)
        self.lframe.pack()
        self.startG()
    def startG(self):    
        self.l1 = Label(self.lframe,text="Card Number",width=15,height=2);
        self.l1.grid(row=0,column=0,padx=10,pady=20)
        self.login = Button(self.lframe,text="Login", fg="black",height=2,width=20,command = self.login)
        self.login.grid(row=0,column=1,padx=10,pady=50)

    def login(self):
            self.l1.destroy()
            self.login.destroy()
            self.l2 = Label(self.lframe,text="User ID  : ",height=2)
            self.l2.grid(row=0,columnspan=2,pady=10,padx=10)
            self.logout = Button(self.lframe, text="Logout !", fg="black",height=2,width=15,command = self.logout)
            self.logout.grid(row=0,column=2,pady=10,padx=10); 
    def logout(self):
        self.l2.destroy()
        self.logout.destroy()
        self.startG()              

if __name__ == "__main__":
    t  = Test()
    mainloop() 

上面的代码片段将初始 gui 显示为

单击登录后,它变为

单击注销后 GUI 恢复到初始 GUI

现在登录按钮不能用了。

如何解决这个错误?

你的命名是这里的问题。尝试重命名相同的方法、小部件名称。当您编写 self.loginself.logout 时,两者都可能是 class 方法或按钮。只要确保通过提供不同的名称来指定哪个是哪个即可。