Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I close a tkinter window?

Tags:

python

tkinter

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?

like image 1000
Matt Gregory Avatar asked Sep 21 '08 12:09

Matt Gregory


2 Answers

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 
like image 91
aki92 Avatar answered Oct 27 '22 00:10

aki92


def quit()
    root.quit()

or

def quit()
    root.destroy()
like image 36
Matt Gregory Avatar answered Oct 27 '22 00:10

Matt Gregory