首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >无法停止python中的计时器(after和after_cancel)

无法停止python中的计时器(after和after_cancel)
EN

Stack Overflow用户
提问于 2021-02-25 18:37:32
回答 2查看 56关注 0票数 -1

我正在尝试在tkinter GUI中创建一个计时器,它在开始按钮上启动,在停止按钮上停止。我正在使用

.after循环计时器,但我不能正确积分.after_取消..。任何建议都将不胜感激。

代码语言:javascript
复制
#import python modules
import time
import math
from tkinter import *

#Create a root window to work in
root = Tk()
root.title("CNT Synthesis Controller") #title of file

#Create global variables to be stored
global var_status
global current_time
global start_time
current_time = 0

#Create Labels

myLabel_Status_T = Label(root, text="Total time elapsed (hrs:min:sec):")
myLabel_Timer = Label(root, text="00:00:00")

#Locate labels

myLabel_Status_T.grid(row=0, column=0)
myLabel_Timer.grid(row=1, column=0)


#Start button function
def Click_Start():  

    #disable Start Button to prevent re-start
    myButton_Start.config(state=DISABLED)
    
    #initiate time = 0 and start timer
    start_time = time.time()
    global Timer_continue
    Timer_continue = True

    #Timer function
    def Timer():
    
        #determine the amount of time passed since start_time measured
        current_time = int(time.time()-start_time)
        hour = math.floor(current_time/3600)
        minute = math.floor((current_time/60)-(hour*60))
        second = math.floor(current_time-(hour*3600)-(minute*60))       
        #shows time as 00:00:00, i.e. adding in the zeroes where needed
        if hour<10:
            hour=str("0"+str(hour))
        else:
            hour=str(hour)
        if minute<10:
            minute=str("0"+str(minute))
        else:
            minute=str(minute)
        if second<10:
              second=str("0"+str(second))
        else:
              second=str(second)
        #print the time to the label myLabel_Timer
        myLabel_Timer.config(text= hour + ":" + minute + ":" + second)
        #after 1000 ms repeat the Timer function
        #while (myButton_Stop['state'] != tk.DISABLED):

        #Timer_Object=myLabel_Timer.after(1000,Timer)
        if Timer_continue == True:
           root.after(1000,Timer)
        if Timer_continue == False:
           root.after_cancel(Timer)
    
    Timer()

#Stop button function
def Click_Stop():  
    Timer_continue = False
    #disable Stop Button to prevent re-use until program is reset
    myButton_Stop.config(state=DISABLED)    



#Create Buttons
myButton_Start = Button(root,text="Start CNT Synthesis", padx=40, pady=20, fg="white", bg="green", command=Click_Start)
myButton_Stop = Button(root,text="Stop CNT Synthesis", padx=40, pady=20, fg="white", bg="red", command=Click_Stop)
#Locate buttons
myButton_Start.grid(row=2, column=0)
myButton_Stop.grid(row=2, column=1)




root.mainloop()

####----Required添加了文本以使问题“足够长”---#

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-02-26 09:45:26

需要保存由返回的ID.after()并在.after_cancel()停止里面的计时器Click_Stop()功能:

代码语言:javascript
复制
#import python modules
import time
from tkinter import *

#Create a root window to work in
root = Tk()
root.title("CNT Synthesis Controller") #title of file

#Create Labels
myLabel_Status_T = Label(root, text="Total time elapsed (hrs:min:sec):")
myLabel_Timer = Label(root, text="00:00:00")

#Locate labels
myLabel_Status_T.grid(row=0, column=0)
myLabel_Timer.grid(row=1, column=0)

Timer_id = None  # used to store the ID returned by .after()

#Start button function
def Click_Start():  
    #disable Start Button to prevent re-start
    myButton_Start.config(state=DISABLED)
    #enable Stop Button
    myButton_Stop.config(state=NORMAL)
    
    #save the start timer
    start_time = time.time()

    #Timer function
    def Timer():
        global Timer_id
    
        #determine the amount of time passed since start_time measured
        elapsed = int(time.time()-start_time)
        minutes, seconds = divmod(elapsed, 60)
        hours, minutes = divmod(minutes, 60)
        myLabel_Timer.config(text=f"{hours:02}:{minutes:02}:{seconds:02}")

        #after 1000 ms repeat the Timer function
        Timer_id = root.after(1000,Timer) # save the after ID
    
    Timer()

#Stop button function
def Click_Stop():
    if Timer_id:
        root.after_cancel(Timer_id) # cancel the scheduled task
    #disable Stop Button to prevent re-use until program is reset
    myButton_Stop.config(state=DISABLED)  
    #enable Start Button
    myButton_Start.config(state=NORMAL)  

#Create Buttons
myButton_Start = Button(root,text="Start CNT Synthesis", padx=40, pady=20,
                        fg="white", bg="green", command=Click_Start)
myButton_Stop = Button(root,text="Stop CNT Synthesis", padx=40, pady=20,
                       fg="white", bg="red", command=Click_Stop, state=DISABLED) # disable stop button initially
#Locate buttons
myButton_Start.grid(row=2, column=0)
myButton_Stop.grid(row=2, column=1)

root.mainloop()
票数 0
EN

Stack Overflow用户

发布于 2021-02-25 18:50:44

错过全局声明:

代码语言:javascript
复制
def Click_Stop():
    global Timer_continue
    Timer_continue = False
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66366887

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档