[英]How to make a countdown timer for a certain time and date in python?
I'm working on a countdown timer for the next spacex launch with python and tkinter.我正在使用 python 和 tkinter 为下一次 spacex 发射开发倒计时计时器。 The timer is supposed to end at 2020-05-30, 22:30 CEST.计时器应该在 2020-05-30, 22:30 CEST 结束。 I want it to update for every second HOURS:MINUTES:SECONDS.我希望它每秒更新一次 HOURS:MINUTES:SECONDS。 I've tried but all i could come up with is this, which still gives me an error.我试过了,但我能想到的就是这个,它仍然给我一个错误。
import tkinter as tk
from datetime import datetime
import time
HEIGHT = 250
WIDTH = 1000
def timer():
spacex = datetime(2020, 5, 30, 22 - 1, 30, 0).timestamp()
dif = spacex - time.time()
# H:M:S
while (dif >= 0):
dif = spacex - time.time()
textline = str(dif // 3600)[:2] + ":" + str((dif // 60) % 60)[:2] + ":" + str((dif // 1) % 60[:2]
time.sleep(1)
v = str(textline)
label["text"] = v
# TKINTER BELOW
root = tk.Tk()
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()
frame = tk.Frame(root, bg="#808080", bd=20)
frame.place(relwidth=0.6, relheight=0.4, relx=0.2, rely=0.25)
button = tk.Button(root, text="See timer!", font="Arial", command=lambda: timer())
button.place(relheight=0.1, relwidth=0.1)
label = tk.Label(frame, font="Arial")
label.place(relwidth=1, relheight=1)
root.mainloop()
The immediate error is a missing closing parenthesis for str()
on this line:直接错误是这一行缺少str()
的右括号:
... + str((dif // 1) % 60[:2]
But while we're at it, let's use tkinter's own timing mechanism instead of a loop and sleep()
, and use the time formatting functions that Python provides.但是,当我们这样做时,让我们使用 tkinter 自己的计时机制而不是循环和sleep()
,并使用 Python 提供的时间格式化函数。 And boost the font size:并提高字体大小:
import tkinter as tk
from datetime import datetime
import time
WIDTH, HEIGHT = 1000, 250
def timer():
space_x = datetime(2020, 5, 30, 22 - 1, 30, 0).timestamp()
delta = space_x - time.time()
if delta >= 0:
label["text"] = time.strftime("%d day(s), %H:%M:%S", time.localtime(delta))
root.after(1000, timer)
root = tk.Tk()
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()
frame = tk.Frame(root, bg="#808080", bd=20)
frame.place(relwidth=0.6, relheight=0.4, relx=0.2, rely=0.25)
button = tk.Button(root, text="See timer!", font="Arial", command=timer)
button.place(relheight=0.1, relwidth=0.1)
label = tk.Label(frame, font=("Arial", "24", "bold"))
label.place(relwidth=1, relheight=1)
root.mainloop()
Using strftime()
this way makes it only good for a month prior.以这种方式使用strftime()
只能在一个月前使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.