From: Alex T. <al...@tw...> - 2008-03-25 22:40:14
|
James Wilkinson wrote: > I'm in Windows XP, and I'm trying to write something like this: > > > while going: > do stuff > > > def on_startButton_mouseClick(...): > going = 1 > > def on_stopButton_mouseClick(...): > going = 0 > > > That should (might) work, provided you include some important code within the loop (i.e. within "do stuff") - see below. > My problem is where to put the loop. The best example I could find in > the samples was the Gravity program. That program puts the loop in > the startButton handler, and Gravity works fine on my machine.]When I > do that in my program, it works fine until I push the stop button. > Then it freezes up and I have to kill it. I also tried putting the > loop in an on_idle(...) method and got the same results. > > If you have enough info to 'do stuff' right away, you could simply put the loop at the end of your on_initialize() but it's likely that you need to let the user set things up before you are ready to 'do stuff', so you might need a button (e.g. 'Go') and put the loop within its handler. The important thing is that you will be in a tight loop (i.e. everything will freeze) unless you allow a way for the user interaction to happen. The easiest way to do that (see for example the Gravity sample) is to include something like # give the user a chance to click Stop wx.SafeYield(self, True) within the loop. > I got around it finally using a timer and it's handler to replace the > loop completely, but that's no good to me for two reasons: > > More complicated than it needs to be :-) > I think the RIGHT way to do this is to use a thread for the loop, but > that's also too much for beginning students. > > Much too complicated - not just for beginners, but because it's too complicated :-) You only need threads if there is "real work" that could be time consuming needing to happen both in the background and the foreground parts. For simply setting a variable to stop a loop, there is no work, and no need for lengthy processing, in the UI event, so threads are very much overkill. Something along the lines I suggested above, and the Gravity example, should work. If you are having trouble, and if it's not too long or complicated (or secret) include the whole of your code in the next email and we can be more specific. (or simplify 'do stuff' to be something simple like 'print going' and then send the whole code ....) -- Alex Tweedly mailto:al...@tw... www.tweedly.net |