said
said

Reputation: 476

How to exit from Python using a Tkinter Button?

To start off, let me show you my code:

import Tkinter
import tkMessageBox
import time
import sys

def endProgam():
    raise SystemExit
    sys.exit()

top = Tkinter.Tk()
B = Tkinter.Button(top, text = "Hello", command = endProgam)
B.pack()
top.mainloop()

As you can see under endProgram() I have tried 2 types of exit commands, both do not work. I never used them together, I was just trying to show what methods I have used so far. These methods were methods I found here and on other websites, but if I try either, I get this error:

Traceback (most recent call last):
  File "C:\Users\Sa'id\Documents\Learning Programming\Python\Tkinter Tuts.py", line 22, in <module>
    top.mainloop()
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1070, in mainloop
    self.tk.mainloop(n)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 1488, in __call__
    raise SystemExit, msg
SystemExit

I can't seem to find a fix to this and I was hoping maybe someone here could help me. If you need any more details I will gladly provide what you need.

Upvotes: 1

Views: 13788

Answers (1)

W1ll1amvl
W1ll1amvl

Reputation: 1269

There are two functions you should use to quit a window:

  • destroy()
  • quit()

Here you have the code using one of the two:

import Tkinter
import tkMessageBox
import time
import sys

def endProgam():
    # top.quit()
    top.destroy()        

top = Tkinter.Tk()

B = Tkinter.Button(top, text = "Hello", command = endProgam)
B.pack()
top.mainloop()

Upvotes: 6

Related Questions