[Tutor] Stop a long loop in python console or in wxpython?

Alan Gauld alan.gauld at btinternet.com
Mon Jun 8 16:03:01 CEST 2009


"xbmuncher" <xboxmuncher at gmail.com> wrote


> Thanks for the reply Alan. I'm unfamiliar on both methods you suggested. 
> Can
> you give me examples with code of them?

Yes:

In a console(untested):
#############
x = 0
try:
   while True:
      x += 1
      print x
      sleep(0.1)
except KeyboardInterrupt:
    print 'stopped'
#############

in a GUI using tkinter(tested) but wxpython should be similar, it 
definitely has a timer.

###############
from Tkinter import *

# global vars
total = 0
stop = False

def counter():
   global total, stop
   if stop == False:
      print "Starting..."
      for n in range(50):
         total += 1
         result['text'] = "Total = %09s" % total
  print "Total = %09s" % total
      # set timer to call again after 100ms
      tk.after(100, counter)
   else: print "Stopped"

def doStop():
   global stop
   stop = True

tk = Tk()
result = Label(tk, text="Not started yet")
result.pack()
Button(tk,text="Start", command=counter).pack()
Button(tk, text="Stop", command=doStop).pack()

tk.mainloop()
###############

hth,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list