Python Forum

Full Version: Closing window on button click not working
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello all,
I am trying to close/destroy a toplevel window via a button.
When I click on the columns_button, a new toplevel window is created with an save_button and exit_button.
When I click the exit_button, the command new_window.destroy closes the window.
When I click the save_button, the program calls the save_columns routine which calls new_window.destroy but the new_window does not close out.
How do I close the new_window from within the save_columns routine.
Thanks in advance.


from tkinter import *
from tkinter import ttk

def get_columns():
    new_window = Toplevel(mw)
    new_window.wm_title("Select Columns")
    new_window.geometry('450x250+250+150')

    frame1 = Frame(new_window)
    framebot = Frame(new_window)
    frame1.pack(side=TOP,fill=X)
    framebot.pack(side=BOTTOM,fill=X)

    w1 = Label(frame1, text="Select Columns ",font=("Times",16)).pack(side="left")

    exit_button = Button(framebot,text='Exit',font=("Times",16),command=new_window.destroy).pack(side="right")
    save_button = Button(framebot,text='Save/Exit',font=("Times",16),command=lambda:save_columns(new_window)).pack(side="left")

def save_columns(new_window):
    print("Saving Columns")
    new_window.destroy # <<<<<<<< Why does this not destroy the window?

if __name__ == "__main__":
    mw=Tk()
    mw.geometry('450x250+200+150')

    frame1 = Frame(mw)
    framebot = Frame(mw)
    frame1.pack(side=TOP,fill=X)
    framebot.pack(side=BOTTOM,fill=X)

    w2 = Label(frame1, text="Table Name: ",font=("Times",16)).pack(side="left")
    a2 = ttk.Combobox(frame1,width=40,font=("Times",16))
    a2.pack(side="left")

    columns_button = Button(framebot,text='Columns',font=("Times",16),command=get_columns).pack(side="left")
    quit_button = Button(framebot,text='Exit',font=("Times",16),command=mw.quit).pack(side="right")

    mw.mainloop()
Use destroy instead of quit.
destroy has not been called

change
new_window.destroy
to
new_window.destroy()
to make the call.
Thank you for your responses.
I put parens after the new_window.destroy in my save_columns routine and that fixed the problem.
I tried putting parens after the new_window.destroy on my Exit button command and it failed with a bad window pathname error.
They should fix Python so that is is more consistent.
Thanks.
function() executes the function. When binding a function to a button you want the button to execute the function, so you pass the function without parens.