Python Tkinter - closing a child window with an exit button Python Tkinter - closing a child window with an exit button tkinter tkinter

Python Tkinter - closing a child window with an exit button


If you put the new_window into your App2 then you should be fine.

self.newWindow.destroy() 

Destroys the window. This is the right call. The window is closed then and all widgets in the window also get destroyed.

quit() will stop the mainloop() In this case the the program ends at the last line and also destroys everything.

You definitely want to use destroy.

class App2:    newWindow = None    def close_window(self):        print('Close Child window')        if self.newWindow:            try: self.newWindow.destroy()               except (): pass # fill in the error here            self.newWindow = None   def new_window(self):        print('New Window')        self.close_window()        self.newWindow = tk.Toplevel(self.master)        self.app = App2(self.newWindow)        self.newWindow.grab_set()    @classmethod    def start_app(cls):        window = tk.Tk(self.master)        app = App2(window)        return app

You should not acces Tkinter from threads. Have a look at alternatives

I was confused by quit and destroy, too, when I was starting with Tkinter.


In Tk windows are destroyed using the destroy method. So if you have a dialog toplevel and you want to get rid of it you call its destroy() method. Or you can withdraw it in which case the object continues to exist but is no longer on-screen and to re-show it you deiconify() the toplevel frame. It's more common to destroy them though. Here is a simple example creating and destroying a child dialog:

import sysfrom Tkinter import *class App(Frame):    def __init__(self, parent = None):        Frame.__init__(self, parent)        self.grid()        self.button = Button(self, text = "Create Dialog", command=self.CreateDialog)        self.button.grid()    def CreateDialog(self):        dialog = Toplevel(self)        dialog.wm_title("Dialog window")        dialog.wm_transient(self)        dialog.wm_protocol("WM_DELETE_WINDOW", lambda: self.onDeleteChild(dialog))        button = Button(dialog, text="Close", command=lambda: self.onDeleteChild(dialog))        button.grid()    def onDeleteChild(self, w):        w.destroy()def main():    app = App()    app.mainloop()if __name__ == "__main__":    sys.exit(main())

You should also consider looking at using a timer in the code to drive the LED loop rather than a while loop. Take a look at this answer using Tk's after function to run code after an interval. If you re-schedule another after call in the handler, then you can arrange a function to be run at regular intervals and avoid blocking the event handling without requiring additional threads.