faqts : Computers : Programming : Languages : Python : Tkinter

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

7 of 10 people (70%) answered Yes
Recently 4 of 7 people (57%) answered Yes

Entry

How can I implement a "cancel"-button that allows a user to cancel a time-intensive function?

May 20th, 2000 03:23
unknown unknown, Randall Hopper


Problem:

I have a simple graphical user interface written with Tkinter. This
allows a user to call a function by pressing on a button (or something 
like this). The function works for some minutes, somtimes up to an hour.

Solution:

The essence of the problem is you need to have your GUI (Tkinter)
process periodically checking for user events, either by returning to 
the main event loop or calling one of the "check for user events" APIs
(Tkinter's update method for example--though see caveats in the docs).

You have a number of options:

   1) Modify your work function to periodically check for user events.

                       worker() -> check_events()
                                -> check_events()
                                -> check_events()

   2) Change your work function to be event-driven.  That is, to do its 
work in pieces, saving appropriate state betweeen each piece. Just wake 
up to do a slice of work via Tkinter timers, and return to the main 
event loop after each slice to handle user events.

                       tk_timer_event -> worker()
                       tk_timer_event -> worker()
                       tk_timer_event -> worker()

   3) Fork off a subprocess to do the work.
   
   4) Create a thread to do the work.

Which one is simplest really depends on your situation (how much 
coupling there is between the GUI "thread" and the compute "thread", for 
example, using the term thread loosely here).