How to only close TopLevel window in Python Tkinter?

Viewed 20755

Use the Python Tkinter , create a sub-panel (TopLevel) to show something and get user input, after user inputed, clicked the "EXIT" found the whole GUI (main panel) also destory. How to only close the toplevel window?

from tkinter import *

lay=[]
root = Tk()
root.geometry('300x400+100+50')

def exit_btn():
    top = lay[0]
    top.quit()
    top.destroy()

def create():
    top = Toplevel()
    lay.append(top)

    top.title("Main Panel")
    top.geometry('500x500+100+450')
    msg = Message(top, text="Show on Sub-panel",width=100)
    msg.pack()

    btn = Button(top,text='EXIT',command=exit_btn)
    btn.pack()

Button(root, text="Click me,Create a sub-panel", command=create).pack()
mainloop()
5 Answers

This seemed to work for me:

from tkinter import *

lay=[]
root = Tk()
root.geometry('300x400+100+50')

def create():

    top = Toplevel()
    lay.append(top)

    top.title("Main Panel")
    top.geometry('500x500+100+450')
    msg = Message(top, text="Show on Sub-panel",width=100)
    msg.pack()

    def exit_btn():

        top.destroy()
        top.update()

    btn = Button(top,text='EXIT',command=exit_btn)
    btn.pack()


Button(root, text="Click me,Create a sub-panel", command=create).pack()
mainloop()

Your only mistake is that you're calling top.quit() in addition to calling top.destroy(). You just need to call top.destroy(). top.quit() will kill mainloop, causing the program to exit.

You can't close to root window. When you will close root window, it is close all window. Because all sub window connected to root window.

You can do hide root window.

Hide method name is withdraw(), you can use show method for deiconify()

# Hide/Unvisible
root.withdraw()

# Show/Visible
root.deiconify()

you can use lambda function with the command it's better than the normal function for your work

ex)

btn = Button(top,text='EXIT',command=exit_btn)

change the exit_btn to lambda :top.destroy()

In my case, I passed a callback function from the parent class, and once the submit button is clicked it will the callback function passing the return values.

The callback function will call the destroy method on the top-level object, thus in that way you'll close the frame and have the return value.

Related