TKinter - How to stop a loop with a stop button?
<p>I have this program which beeps every second until it's stopped. The problem is that after I press "Start" and the beeps starts, I cannot click the "Stop" button because the window freezes. Any help is welcome.</p>

<pre><code>#!/usr/bin/python
import Tkinter, tkMessageBox, time, winsound, msvcrt

running = True

Freq = 2500
Dur = 150

top = Tkinter.Tk()
top.title('MapAwareness')
top.geometry('200x100') # Size 200, 200

def start():
    sec = 0
    while running:
        if sec % 1 == 0:
            winsound.Beep(Freq, Dur)

        time.sleep(1)
        sec += 1

def stop():
    running = False

startButton = Tkinter.Button(top, height=2, width=20, text ="Start", command = start)
stopButton = Tkinter.Button(top, height=2, width=20, text ="Stop", command = stop)

startButton.pack()
stopButton.pack()

top.mainloop()
</code></pre>

<p>The problem is that the while loop in <code>start()</code> blocks the GUI handler <code>mainloop()</code>.  Try using <code>Tk.after()</code> in <code>start()</code>:</p>

<pre><code>def start(force=True):
    global running
    if force:
        running = True
    if running:
        winsound.Beep(Freq, Dur)
        top.after(1000, start, False)
</code></pre>

<p>And change <code>stop()</code>:</p>

<pre><code>def stop():
    global running
    running = False
</code></pre>

python tkinter