tags:

views:

2520

answers:

3

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

from Tkinter import *

def quit():
    ???

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

How should I define the quit() routine?

+5  A: 
def quit()
    global root
    root.quit()

or

def quit()
    global root
    root.destroy()
Matt Gregory
The 'global' declaration there is not necessary. You only need 'global' if you wish to assign to a global name from within a function. 'root.quit()' merely looks up root, it does not assign to root.
Thomas Wouters
Really! I didn't know that. Thanks!
Matt Gregory
+3  A: 

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.

dF
+2  A: 

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()