Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 647
baliao Avatar asked Jan 17 '19 22:01

baliao


3 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()
like image 170
visualnotsobasic Avatar answered Sep 28 '22 17:09

visualnotsobasic


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.

like image 20
Bryan Oakley Avatar answered Sep 28 '22 16:09

Bryan Oakley


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()
like image 41
Fatih Mert Doğancan Avatar answered Sep 28 '22 15:09

Fatih Mert Doğancan