How to only close TopLevel window in Python Tkinter?

16,212

Solution 1

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()

Solution 2

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.

Solution 3

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()
Share:
16,212
baliao
Author by

baliao

Updated on July 29, 2022

Comments

  • baliao
    baliao almost 2 years

    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()
    
  • baliao
    baliao over 5 years
    Much thanks for you sharing the solution, I can use it in another case.
  • user32882
    user32882 over 2 years
    Why call update?