Python GUI wrapper for a long operation
Jeff Epler
jepler at unpythonic.net
Wed Apr 21 08:22:59 EDT 2004
To interleave calculation and GUI activity in the same thread, simply
call the "update_idletasks" or "update" method on any Tk widget at
intervals.
update_idletasks() will do things like repaint windows that have been
uncovered or resized, or when the information displayed on a widget has
changed.
update() will handle all events, just like mainloop(), but returns as soon
as there's no longer an event to handle.
Jeff
from Tkinter import *
import time
class StupidProgress(Label):
def __init__(self, master):
Label.__init__(self, master, text="0%")
def progress(self, percent):
self.configure(text="%s%%" % percent)
self.update()
abort = 0
def calculation():
b.configure(state=DISABLED)
c.configure(state=NORMAL)
for i in range(100):
print "calculation"
time.sleep(.1) # represents doing .1 second of calculation
if check_abort():
b.configure(state=NORMAL)
c.configure(state=DISABLED)
l.progress(0)
return
l.progress(i)
l.progress(100)
c.configure(state=DISABLED)
m.configure(text="Result: 42")
def check_abort():
global abort
if not abort: return 0
abort = 0
return 1
def do_abort():
global abort
abort = 1
app = Tk()
l = StupidProgress(app)
m = Label(app, text="(No result)")
b = Button(app, command=calculation, text="Find answer")
c = Button(app, command=do_abort, text="Never mind", state=DISABLED)
l.pack()
m.pack()
b.pack()
c.pack()
app.mainloop();
More information about the Python-list
mailing list