baliao
baliao

Reputation: 173

How to only close TopLevel window in Python Tkinter?

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

Upvotes: 9

Views: 34943

Answers (5)

Jamal Alkelani
Jamal Alkelani

Reputation: 618

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.

Upvotes: 0

MR. Ant
MR. Ant

Reputation: 11

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

Upvotes: 1

visualnotsobasic
visualnotsobasic

Reputation: 428

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

Upvotes: 12

Bryan Oakley
Bryan Oakley

Reputation: 386352

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.

Upvotes: 9

Fatih Mert Doğancan
Fatih Mert Doğancan

Reputation: 1092

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

Upvotes: 3

Related Questions