[英]cannot figure out making timer in tkinter
I haven't added much to my code so far but what it is supposed to do is decrement variable time_1 by 1 every second, it does not do this and instead it turns to 0 almost immediately.到目前为止,我还没有向我的代码添加太多内容,但它应该做的是每秒将变量 time_1 递减 1,它不会这样做,而是几乎立即变为 0。 What am I doing wrong?我究竟做错了什么?
import tkinter as tk
import threading
from tkinter import ttk
root = tk.Tk()
root.title("Chess Timer")
root.minsize(250,250)
time_1 = 60.0
time_2 = 60.0
timer_1 = ttk.Label(root, text=time_1)
timer_1.grid(column=1, row=0)
timer_2 = ttk.Label(root, text=time_2)
timer_2.grid(column=2, row=0)
def update():
timer_1.config(text=time_1)
timer_2.config(text=time_2)
while time_1 and time_2 > 0:
time_1 -= 1
threading.Timer(1.0,update).start()
root.mainloop()
I'm new to python, any help is appreciated!我是 python 的新手,不胜感激!
The problem here is in the while
loop.这里的问题在于while
循环。 The call to threading.Timer(1.0, update).start()
does not make the loop wait one second;对threading.Timer(1.0, update).start()
的调用不会使循环等待一秒钟; it makes the calls to update
wait one second.. Thus, 60 1-second timers are set almost immediately, and all update the labels at about the same time.它使update
调用等待一秒钟。因此,几乎立即设置了 60 个 1 秒计时器,并且几乎同时更新标签。 The while
loop, meanwhile, subtracts both time_1
down to zero in almost an instant, since it's not being hindered by the timer.同时, while
循环几乎在瞬间将time_1
减去为零,因为它没有受到计时器的阻碍。
For something like this, you don't need to use the threading
module.对于这样的事情,您不需要使用threading
模块。 You can just use the root.after()
function to call your function after a set number of milliseconds.您可以使用root.after()
function 在设定的毫秒数后调用您的 function 。 Here is what your code would look like using root.after()
:这是您的代码使用root.after()
的样子:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
root.title("Chess Timer")
root.minsize(250,250)
time_1 = 60.0
time_2 = 60.0
timer_1 = ttk.Label(root, text=time_1)
timer_1.grid(column=1, row=0)
timer_2 = ttk.Label(root, text=time_2)
timer_2.grid(column=2, row=0)
def update():
global time_1, timer_1, root
time_1 -= 1
timer_1.config(text=time_1)
root.after(1000, update)
update()
root.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.