计时器的Tkinter代码使应用程序崩溃(python)

1 人关注

我正在为我的测验应用程序创建一个定时器,我决定先在一个单独的程序中进行试验。 然而,当我运行下面的代码并按下 "开始计时器 "按钮时,该应用程序根本停止响应 我被迫通过任务管理器关闭它

from tkinter import *
import time
root=Tk()
root.geometry('{}x{}'.format(300,200))
lb=Label(root,text='')
lb.pack()
def func(h,m,s):
    lb.config(text=str(h)+':'+str(m)+':'+str(s))
    time.sleep(1)
    func(h,m,s)
    if s==59:
bt=Button(root,text='start timer',command=lambda:func(0,0,0))
bt.pack()
root.mainloop()
    
4 个评论
不要在tkinter中使用 time.sleep 。请使用 root.after See here 欲了解更多信息。
@Henry didn't help
你尝试了什么?
我用root.after(1000, func1)替换了time.sleep(1),并在func1中加入了s+=1。
python
tkinter
timer
crash
darthchild
darthchild
发布于 2021-03-19
1 个回答
Henry
Henry
发布于 2021-03-19
已采纳
0 人赞同

你需要使用 root.after 而不是 time.sleep 。下面是 另一个答案 关于制作一个计时器。这是它应用于你的代码的样子。

from tkinter import *
import time
root=Tk()
root.geometry('{}x{}'.format(300,200))
lb=Label(root,text='')
lb.pack()
def func(h,m,s):
    lb.config(text=str(h)+':'+str(m)+':'+str(s))
    if s==59:
    root.after(1000, lambda: func(h,m,s))