[Tutor] Closing GUI program

Michael H. Goldwasser goldwamh at slu.edu
Fri Dec 28 15:38:27 CET 2007


Hi Jim,

  The problem with your code is that Tk's mainloop continues to run
  even though you have closed the window.  The cleaner way to close
  such a GUI program is to explicitly stop the main loop and the
  Python interpreter at the appropriate time.

  In this particular case, you may provide a callback function that is
  triggered on the event of a window being manually closed by the user.

  Here's a revised version of your program that should work better,
  even within IDLE.  Of course, there is still some system dependency
  among the program, IDLE, and the underlying operating system.

  Some interesting reading is at  http://www.3dartist.com/WP/python/tknotes.htm

With regard,
Michael

-------------------------------------------
from Tkinter import Tk,Label

def onClose():
    root.destroy()   # stops the main loop and interpreter

root = Tk()
root.protocol("WM_DELETE_WINDOW", onClose)  # handle event when window is closed by user
z = Label(root, text="Hello World!")
z.grid()
root.mainloop()
-------------------------------------------

On Friday December 28, 2007, Jim Morcombe wrote: 

>    Oops!  Here's the program:
>    ---------------------------
>    from Tkinter import *     
>    
>    root = Tk()
>    z = Label(root, text="Hello World!")
>    z.grid()
>    root.mainloop()
>    ------------------------------
>    
>    Jim
>    
>      ----- Original Message ----- 
>      From: Jim Morcombe 
>      To: python tutor mailing list 
>      Sent: Friday, December 28, 2007 3:51 PM
>      Subject: [Tutor] Closing GUI program
>    
>    
>      I have copied the following program.  When I run it, (By pressing F5 from IDLE), it displays the "Hello world" message.
>    
>      When I close the window, the "Hello world" message disappears, but it seems that the program is still running, because when I close the shell, i get the message "The program is still running.  Do you want to kill it?"
>    
>      How do I get the program to terminate when the window is closed?
>    
>      Jim



More information about the Tutor mailing list