TKinter - How to stop a loop with a stop button?

前端 未结 5 1638
礼貌的吻别
礼貌的吻别 2020-12-20 20:16

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 becaus

5条回答
  •  攒了一身酷
    2020-12-20 21:06

    You code have top.mainloop() which has a while loop running inside it and on top of that you also have a while loop inside def start():. So it is like loop inside loop.

    You can create a function that does what you want for the body of the loop. It should do exactly one iteration of the loop. Once it is done, it needs to arrange for itself to be called again some time in the future using after. How far in the future defines how fast your loop runs.

    And you can then use after_cancel to cancel the event. Below code worked for me

    import Tkinter, tkMessageBox, time, winsound, msvcrt
    
    Freq = 2500
    Dur = 150
    
    top = tkinter.Tk()
    top.title('MapAwareness')
    top.geometry('200x100') # Size 200, 200
    
    def start():
        global job1
        if running == True:
            winsound.Beep(Freq, Dur)
            job1 = top.after(1000, start)  # reschedule event in 1 seconds
    
    def stop():
        global job1
        top.after_cancel(job1)
    
    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.after(1000, start)
    top.mainloop()
    

提交回复
热议问题