Detect events positively

Gustavo Cordova gcordova at hebmex.com
Fri Jun 7 12:52:53 EDT 2002


> 
> Hello,
> 
> The following code display two button:
> 
> from Tkinter import *
> def Calculate(event = None):
>         while 1:
>                 pass

This loop will never exit, hence, will never
return control to Tkinter (and your GUI).

> def Exit(event = None):
>         import sys
>         sys.exit(0)
> root = Tk()
> btn_cal = Button(root, text="calculate", command = Calculate)
> btn_cal.pack()
> btn_exit = Button(root, text="exit", command = Exit)
> btn_exit.pack()
> root.mainloop()
> 
> if clicked the "calculate" button, the program will fall in a 
> loop that will never end. So program will not response to clicking
> to the "exit" button, so it cannot be terminated normally. If we
> don't use multithread, can we add some code in the loop of the
> function Calculate to let it exit the loop after the user clicks
> the "exit" button or press a "Esc" key?
> 

Well, you're little program is doing what you asked
it to do, :-)

You can use some multithreading, like:

# This function does all the hard work.
def Do_Calculations():
   do_lotsa_calculations()
   save_results_somewhere()
   set_finished_flag()
   raise SystemExit()

def Calculate(event=None):
   if calculation_thread_not_set():
      import thread
      set_calculation_thread_flag()
      thread.start_new_thread(Do_Calculations, (,))

Now the calculations are done independantly from the GUI
management thread; this is good. But, you should NOT DO ANY
GUI MANIPULATION from the thread doing the calculations,
because Tkinter WILL CRASH AND BURN. Hence, the set_finished_flag()
thing, where you inform the main thread by any means you
like that the calculations are done; that flag can be
picked up by your main thread, which can update the GUI.

Good luck :-)

> Many thanks from, 
> Xiao-Qin Xia
> 

-gustavo





More information about the Python-list mailing list