How do I close a tkinter window?

PythonTkinter

Python Problem Overview


How do I end a Tkinter program? Let's say I have this code:

from Tkinter import *

def quit():
    # code to exit

root = Tk()
Button(root, text="Quit", command=quit).pack()
root.mainloop()

How should I define the quit function to exit my application?

Python Solutions


Solution 1 - Python

You should use destroy() to close a tkinter window.

from Tkinter import *

root = Tk()
Button(root, text="Quit", command=root.destroy).pack()
root.mainloop()

Explanation:

root.quit()

The above line just Bypasses the root.mainloop() i.e root.mainloop() will still be running in background if quit() command is executed.

root.destroy()

While destroy() command vanish out root.mainloop() i.e root.mainloop() stops.

So as you just want to quit the program so you should use root.destroy() as it will it stop the mainloop().

But if you want to run some infinite loop and you don't want to destroy your Tk window and want to execute some code after root.mainloop() line then you should use root.quit(). Ex:

from Tkinter import *
def quit():
    global root
    root.quit()

root = Tk()
while True:
    Button(root, text="Quit", command=quit).pack()
    root.mainloop()
    #do something

Solution 2 - Python

def quit()
    root.quit()

or

def quit()
    root.destroy()

Solution 3 - Python

import tkinter as tk

def quit(root):
    root.destroy()

root = tk.Tk()
tk.Button(root, text="Quit", command=lambda root=root:quit(root)).pack()
root.mainloop()

Solution 4 - Python

I think you wrongly understood the quit function of Tkinter. This function does not require you to define.

First, you should modify your function as follows:

from Tkinter import *
root = Tk()
Button(root, text="Quit", command=root.quit).pack()
root.mainloop()

Then, you should use '.pyw' suffix to save this files and double-click the '.pyw' file to run your GUI, this time, you can end the GUI with a click of the Button, and you can also find that there will be no unpleasant DOS window. (If you run the '.py' file, the quit function will fail.)

Solution 5 - Python

The usual method to exit a Python program:

sys.exit()

(to which you can also pass an exit status) or

raise SystemExit

will work fine in a Tkinter program.

Solution 6 - Python

Illumination in case of confusion...

def quit(self):
    self.destroy()
    exit()

A) destroy() stops the mainloop and kills the window, but leaves python running

B) exit() stops the whole process

Just to clarify in case someone missed what destroy() was doing, and the OP also asked how to "end" a tkinter program.

Solution 7 - Python

In case anyone wants to bind their Escape button to closing the entire GUI:

master = Tk()
master.title("Python")

def close(event):
    sys.exit()

master.bind('<Escape>',close)
master.mainloop()

Solution 8 - Python

you only need to type this:

root.destroy()

and you don't even need the quit() function cause when you set that as commmand it will quit the entire program.

Solution 9 - Python

The easiest way would be to click the red button (leftmost on macOS and rightmost on Windows). If you want to bind a specific function to a button widget, you can do this:

class App:
    def __init__(self, master)
        frame = Tkinter.Frame(master)
        frame.pack()
        self.quit_button = Tkinter.Button(frame, text = 'Quit', command = frame.quit)
        self.quit_button.pack()

Or, to make things a little more complex, use protocol handlers and the destroy() method.

import tkMessageBox

def confirmExit():
    if tkMessageBox.askokcancel('Quit', 'Are you sure you want to exit?'):
        root.destroy()
root = Tk()
root.protocol('WM_DELETE_WINDOW', confirmExit)
root.mainloop()

Solution 10 - Python

you dont have to open up a function to close you window, unless you're doing something more complicated:

from Tkinter import *

root = Tk()
Button(root, text="Quit", command=root.destroy).pack()
root.mainloop()

Solution 11 - Python

In idlelib.PyShell module, root variable of type Tk is defined to be global

At the end of PyShell.main() function it calls root.mainloop() function which is an infinite loop and it runs till the loop is interrupted by root.quit() function. Hence, root.quit() will only interrupt the execution of mainloop

In order to destroy all widgets pertaining to that idlelib window, root.destroy() needs to be called, which is the last line of idlelib.PyShell.main() function.

Solution 12 - Python

I normally use the default tkinter quit function, but you can do your own, like this:

from tkinter import *
from tkinter.ttk import *

window = Tk()
window.geometry('700x700') # 700p x 700p screen

def quit(self):
    proceed = messagebox.askyesno('Quit', 'Quit?')
    proceed = bool(proceed) # So it is a bool

    if proceed:
        window.quit()
    else:
        # You don't really need to do this
        pass

btn1 = Button(window, text='Quit', command=lambda: quit(None))

window.mainloop()

Solution 13 - Python

For menu bars:

def quit():
    root.destroy()

menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)

filemenu.add_separator()

filemenu.add_command(label="Exit", command=quit)
menubar.add_cascade(label="menubarname", menu=filemenu)
root.config(menu=menubar)
root.mainloop()

Solution 14 - Python

I use below codes for the exit of Tkinter window:

from tkinter import*
root=Tk()
root.bind("<Escape>",lambda q:root.destroy())
root.mainloop()

or

from tkinter import*
root=Tk()
Button(root,text="exit",command=root.destroy).pack()
root.mainloop()

or

from tkinter import*
root=Tk()
Button(root,text="quit",command=quit).pack()
root.mainloop()

or

from tkinter import*
root=Tk()
Button(root,text="exit",command=exit).pack()
root.mainloop()

Solution 15 - Python

Code snippet below. I'm providing a small scenario.

import tkinter as tk
from tkinter import *

root = Tk()

def exit():
    if askokcancel("Quit", "Do you really want to quit?"):
        root.destroy()

menubar = Menu(root, background='#000099', foreground='white',
               activebackground='#004c99', activeforeground='white')

fileMenu = Menu(menubar,  tearoff=0, background="grey", foreground='black',
                activebackground='#004c99', activeforeground='white')
menubar.add_cascade(label='File', menu=fileMenu)

fileMenu.add_command(label='Exit', command=exit)

root.config(bg='#2A2C2B',menu=menubar)

if __name__ == '__main__':
    root.mainloop()

I have created a blank window here & add file menu option on the same window(root window), where I only add one option exit.

Then simply run mainloop for root.

Try to do it once

Solution 16 - Python

Of course you can assign the command to the button as follows, however, if you are making a UI, it is recommended to assign the same command to the "X" button:

def quit(self): # Your exit routine
   self.root.destroy()

self.root.protocol("WM_DELETE_WINDOW", self.quit) # Sets the command for the "X" button 

Button(text="Quit", command=self.quit) # No ()

Solution 17 - Python

There is a simple one-line answer:

Write - exit() in the command

That's it!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMatt GregoryView Question on Stackoverflow
Solution 1 - Pythonaki92View Answer on Stackoverflow
Solution 2 - PythonMatt GregoryView Answer on Stackoverflow
Solution 3 - PythonkaytecView Answer on Stackoverflow
Solution 4 - PythonTreeDoNotSplitView Answer on Stackoverflow
Solution 5 - PythondF.View Answer on Stackoverflow
Solution 6 - PythonMartin GuilesView Answer on Stackoverflow
Solution 7 - PythonNukyiView Answer on Stackoverflow
Solution 8 - PythonBruhDevView Answer on Stackoverflow
Solution 9 - PythonIan GabaraevView Answer on Stackoverflow
Solution 10 - PythonGonzalezView Answer on Stackoverflow
Solution 11 - PythonRADView Answer on Stackoverflow
Solution 12 - PythonUnlinedBusView Answer on Stackoverflow
Solution 13 - PythonLenyaKapView Answer on Stackoverflow
Solution 14 - PythonkouroshView Answer on Stackoverflow
Solution 15 - PythonOzziusView Answer on Stackoverflow
Solution 16 - PythonGeetansh GView Answer on Stackoverflow
Solution 17 - PythonsnooksoView Answer on Stackoverflow