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

前端 未结 5 1640
礼貌的吻别
礼貌的吻别 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 20:58

    I used thread and global variable to fit your need. Not so complicated if you understand how they work. Just an addition of few lines and minor change to your existing line, and it works. Look through to see the changes made to your original code.

        #!/usr/bin/python
        import tkinter
        from tkinter import messagebox
        import time, winsound, msvcrt
        from threading import Thread
    
        running = True
    
        Freq = 2500
        Dur = 150
    
        top = tkinter.Tk()
        top.title('MapAwareness')
        top.geometry('200x100') # Size 200, 200
    
        def button_click():
            global running  #create global
            running = True
    
            # Create new thread
            t = Thread(target = start)
            # Start new thread
            t.start()
    
        def start():
            sec = 0
            while running:
                if running == False:
                    break
                if sec % 1 == 0:
                    winsound.Beep(Freq, Dur)
    
                time.sleep(1)
                sec += 1
    
        def stop():
            global running  #create global
            running = False
    
        startButton = tkinter.Button(top, height=2, width=20, text ="Start", command = button_click) #Change to call button_click instead start
        stopButton = tkinter.Button(top, height=2, width=20, text ="Stop", command = stop)
    
        startButton.pack()
        stopButton.pack()
    
        top.mainloop()
    

提交回复
热议问题