Search code examples
pythontkinterdestroy

Can't close a window and keep other open


I am trying to open a second window and then run some code and close the second window on the button event. I have tried every example that I can find and I still get an attribute error. I am pretty new to this.

I stripped out most of the code so that it's easier to read.

#   ADD NEW PASSWORD
def add_pass():

    add_pass = Toplevel()
    add_pass.title("Enter New Password")
    add_pass.geometry('500x700')
    # add_pass.resizable(0, 0)

    
    Add_Button = Button(add_pass, text="Enter", font=("normal", 14), 
    command=add_butt)
    Add_Button.grid(row=12, column=2, pady=30)
    
    
def add_butt():

    print(Person_Entry.get())

    # Create a database or connect to one
    conn = sqlite3.connect('Pass.db')

    c = conn.cursor()                
                        
    # WRITE TEXT BOXES TO SQLITE3 DB USING VARIABLES. 
    PassData = [(Seq_Entry.get(), Person_Entry.get(), Name_Entry.get(), 
    URL_Entry.get(), Username_Entry.get(), Password_Entry.get(), Hint1_Entry.get(), 
    Hint2_Entry.get(), Hint3_Entry.get(), Notes_Entry.get())]
    
    for element in PassData:
        c.execute("INSERT INTO Passwords VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", 
    element)
        

    # Commit Changes
    conn.commit()

    # Close Connection
    conn.close()

    add_pass.destroy()

root = Tk()

root.geometry('500x500')
root.title('Password Saver')
my_menu = Menu(root)
 

root.mainloop()

Solution

  • You got several options here to achieve this, the easiest way to go would be to use lambda and pass a reference of your window, stored with the variable add_pass in the namespace of the function add_pass through the interface of your function add_butt. Passing an argument through a button command in tkinter can be achieved in different ways but I prefer lambda.

    The changes would look like this:

    def add_pass(): 
        ..
        Add_Button = Button( ..,command=lambda window=add_pass: add_butt(window))
    
    def add_butt(window):
        window.destroy()
       ...
    

    Addition advice:

    Don't use wildcard imports

    Don't use the same variable name more than once

    See explanation And also take a look at PEP 8