akrishnamo
akrishnamo

Reputation: 459

Why is Tkinter Toplevel object being destroyed?

In the code below, tk is not the parent of the Toplevel object that is created by the function launch(). However, when I destroy tk using tk.destroy(), the Toplevel window vanishes.

Is the Toplevel widow being destroyed? If so, how is Toplevel.destroy() being called?

from tkinter import *


def launch():
    Toplevel()

tk = Tk()

frame = Frame(tk, relief="ridge", borderwidth=2)
frame.pack(fill="both", expand=1)
label = Label(frame, text="Hello, World")
label.pack(fill=X, expand=1)

button1 = Button(frame, text="Exit", command=tk.destroy)
button2 = Button(frame, text="Launch", command=launch)

button1.pack(side="bottom")
button2.pack(side="bottom")

tk.mainloop()

Upvotes: 1

Views: 852

Answers (2)

nbro
nbro

Reputation: 15837

What keeps your application running is the mainloop of the Tk instance, which is the parent of all widgets. When you destroy it, all the widgets are also destroyed.


Keeping in mind that for each Tk instance, there's an associated Tcl interpreter, I will try to give a more detailed answer on what happens when you close a window, based on the docs strings of the Tk and associated classes and methods of the tkinter module.

Tk derives from 2 classes: Misc and Wm. In the Misc class, you can find the interface and the documentation for the quit method:

def quit(self):
    """Quit the Tcl interpreter. All widgets will be destroyed."""
    self.tk.quit()

You can find under the destroy method of the Tk class the following:

def destroy(self):
    """Destroy this and all descendants widgets. This will
    end the application of this Tcl interpreter."""

The destroy method in the Tk class calls also, at certain point, the destroy method of the Misc class, and there you can find also another documentation:

def destroy(self):
    """Internal function.
    Delete all Tcl commands created for
    this widget in the Tcl interpreter."""

Which does not say that also the Tcl interpreter is stopped (like in the quit method described above).

When constructing a Tk instance, a method called _loadtk is called. In this method, it is set the protocol when the Tk window is closed:

self.protocol("WM_DELETE_WINDOW", self.destroy)

as you can see, destroy (and not quit) is associated with the closing event of the window.


This all means that when you close the window, the Tk instance and all its children are destroyed, but the Tcl interpreter is not stopped.

Upvotes: 5

Adam Smith
Adam Smith

Reputation: 54163

Tkinter.Tk is the big poppa granddaddy of all tkinter windows. It runs the logic and communicates with the OS. When it goes -- they all go.

Upvotes: 3

Related Questions