Hi,

this is my first post here at Daniweb. Seems like an active and friendly environment.
I have very limited experience with programming in general, and even more so with GUI programming.
As the title suggests, I want to stop a while loop by the use of buttons.
When I press the start button, the program prints out "True" on the command window (I'm using windows). I am unable to press the stop button, the program just continues to print "True". I have to abort it to be able to stop.
How can I fix this?

Also, how can I print "True" on the panel instead of command window?

Thanks

import wx

class whileLoop(wx.Frame):

    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id,'whileLoop', size=(300,200))
        panel = wx.Panel(self)
        
        startButton = wx.Button(panel, label="start", pos=(10,10), size=(40,30))
        self.Bind(wx.EVT_BUTTON, self.startLoop, startButton)
        
        stopButton = wx.Button(panel, label="stop", pos=(60,10), size=(40,30))
        self.Bind(wx.EVT_BUTTON, self.stopLoop, stopButton)
        
    def startLoop(self,event):
        global flag
        flag = True
        while flag:
            if flag == False:
                break
            else:
                print "True"
       
    def stopLoop(self,event):
        global flag
        flag = False
        
if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = whileLoop(parent=None,id=-1)
    frame.Show()
    app.MainLoop()

Take out the while, the mainloop is your loop. Set timer event for printing if flag is set. Button event just sets/unsets flag.

Take a real close look at the threading examples on this page (absolutely brilliant tutorial): http://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/

I recently developed wxPython code (using the first example in the link above) which updates a clock in the GUI every one second, and break from the loop by setting a flag value as you have in your code. You're close, but you'll definitely want to invest time into learning threading well.

Comments
Nice link

Thanks for the replies guys. Looks like threading is the way to go. Thank you for the link convoluted, I'm having a look at the code. It might take some time before I understand it though :)

There a re several ways.

I think the most easy and accurate is the wx.Timer() method.
Very simple and handy.

eg:

timer=wx.Timer(parent,-1)

# Then you use the 

timer.Stop()
#or 
timer.Start()

## In your events method.

check it out ;)

This article has been dead for over six months. Start a new discussion instead.