简体   繁体   English

如何让计时器显示秒数?

[英]How can I make a timer display seconds?

I read that a countdown timer could be made with time.sleep().我读到可以使用 time.sleep() 制作倒数计时器。 This is my attempt.这是我的尝试。 I can print the seconds to the idle, but not to the Tkinter window.我可以将秒数打印到空闲状态,但不能打印到 Tkinter 窗口。 Is there a hack around it?它周围有黑客吗?

import time; from tkinter import *

sec = 11
def start(timer):
    print(countDown(sec,timer))

def countDown(sec,timer):
    while sec >= 0:
        print(sec)
        if sec > 9:
            timer.configure(text = str(sec)) #'two digits'
        elif sec > 0:
            timer.configure(text = '0'+str(sec)) #'one digit'
        else:
            timer.configure(text = 'GAME OVER!')
        sec -= 1
        time.sleep(1)

win = Tk()
win.configure(bg='black')
header = Label(win, text="Game Timer", fg='blue', bg='black', font=('Arial Bold',14))
header.pack()
timer = Label(win, relief=SUNKEN, fg='white', bg='black', font=('Arial',14))
timer.pack(fill=BOTH, expand=1)
btn = Button(win,text='Start', command= lambda: start(timer))
btn.pack()
win.mainloop()

So a few things we can do to improve this.所以我们可以做一些事情来改善这一点。

  1. Instead of trying to manage the format using an if statement we can use strftime to format out time.我们可以使用strftime来格式化时间,而不是尝试使用 if 语句来管理格式。 This can be done for say Days, Hours, Min, Sec and so on but right now we just need Seconds.这可以用于说天、小时、分钟、秒等,但现在我们只需要秒。

  2. You want to avoid while and sleep() while in the same thread as tkinter.您想避免whilesleep()与 tkinter 在同一线程中。 This is because those 2 methods will block the main loop so you will never see the time displayed and only ever see GAME OVER once the while loop and sleep has completed due to both of them blocking the mainloop.这是因为这 2 种方法将阻塞主循环,因此您将永远不会看到显示的时间,并且只有在 while 循环和睡眠完成后才能看到GAME OVER ,因为它们都阻塞了主循环。

  3. Write your imports on new lines and use import tkinter as tk instead of * .将您的导入写在新行上,并使用import tkinter as tk而不是* This will help prevent overwriting anything.这将有助于防止覆盖任何内容。

  4. we can remove one of your function as it is an extra step that is not needed.我们可以删除您的功能之一,因为它是不需要的额外步骤。

  5. to manage a timed loop in tkinter we can use after() .要在 tkinter 中管理定时循环,我们可以使用after()

Try this:尝试这个:

import tkinter as tk
import time


def count_down(sec):
        if sec > 0:
            timer.configure(text=time.strftime('%S', time.gmtime(sec)))
            win.after(1000, lambda: count_down(sec-1))
        else:
            timer.configure(text='GAME OVER!')


win = tk.Tk()
win.configure(bg='black')
sec = 11

header = tk.Label(win, text="Game Timer", fg='blue', bg='black', font=('Arial Bold', 14))
timer = tk.Label(win, relief='sunken', fg='white', bg='black', font=('Arial', 14))
btn = tk.Button(win, text='Start', command=lambda: count_down(sec))

header.pack()
timer.pack(fill='both', expand=1)
btn.pack()
win.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM