Tkinter - Reading widgets during a callback

sismex01 at hebmex.com sismex01 at hebmex.com
Mon Dec 9 16:57:19 EST 2002


> From: andrewnewsgroup at hotmail.com [mailto:andrewnewsgroup at hotmail.com]
> Sent: Monday, December 09, 2002 2:55 PM
> 
> Hi,
> Here is my Tkinter GUI problem.  I have two buttons, "Start
> Processing" and "Abort".  When the user hits "Start Processing",
> the callback for this button runs - it performs some computational
> heavy processing that goes on for minutes.  Sometimes the user may
> want to abort this processing, so they would like to hit the
> "Abort" button and have the processing stopped.
> 
> I just can't figure out how to implement this functionality in
> Tkinter.  Any ideas??  Once the "start processing" callback runs, I
> don't know how to get the Abort button to interupt the callback.  I
> tried polling the state of the Abort button periodically while in the
> "start processing" callback but the state doesn't get updated until
> the "start processing" callback finishes.  (e.g. currentstate =
> abortButtonHdl.config()[state][4])
> 
> How can one find out what events have occured? or a list of callbacks
> that are queued for execution because multiple buttons have been
> pressed?  Can one prematurely force an executing callback to
> terminate?
> 
> Regards
> Andrew
>

You might need to have a worker thread, to do the computations,
and let the main thread work with the GUI. Something simple,
like this:

#########################
## Example code.
##

import thread, time

# These variables contains the status of the
# calculations thread, and is checked by it.
CANCEL_FLAG = None
RUNNING_FLAG = None

def do_lengthy_calculations(...):
   global RUNNING_FLAG, CANCEL_FLAG
   if RUNNING_FLAG is None:
      RUNNING_FLAG = 1
      while CANCEL_FLAG is None:
         ...
         ...
         ...
      # shutdown calculations.

def StartCB():
   if RUNNING_FLAG is None:
      thread.start_new_thread(do_lengthy_calculations, (), {})
   start["state"] = "disabled"

def CancelCB():
   while RUNNING_FLAG:
      CANCEL_FLAG = 1
      time.sleep(0.05)
   start["state"] = "normal"

<build your gui stuff>
# Start button definition.
start = Tkinter.Button(root, text="Start", command=StartCB)

# Cancel button definition.
cancel = Tkinter.Button(root, text="Cancel", command=CancelCB)
<continue building gui stuff>

root.mainloop()
###########################

So, when you click on "Start", a new thread is launched and
your calculations begin.  When you click on "Cancel", a flag
is raised and your calculations stop, and things get
restored in case you need to do more stuff.

I think this'll work.

-gustavo




More information about the Python-list mailing list