繁体   English   中英

如何让计时器显示秒数?

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

我读到可以使用 time.sleep() 制作倒数计时器。 这是我的尝试。 我可以将秒数打印到空闲状态,但不能打印到 Tkinter 窗口。 它周围有黑客吗?

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()

所以我们可以做一些事情来改善这一点。

  1. 我们可以使用strftime来格式化时间,而不是尝试使用 if 语句来管理格式。 这可以用于说天、小时、分钟、秒等,但现在我们只需要秒。

  2. 您想避免whilesleep()与 tkinter 在同一线程中。 这是因为这 2 种方法将阻塞主循环,因此您将永远不会看到显示的时间,并且只有在 while 循环和睡眠完成后才能看到GAME OVER ,因为它们都阻塞了主循环。

  3. 将您的导入写在新行上,并使用import tkinter as tk而不是* 这将有助于防止覆盖任何内容。

  4. 我们可以删除您的功能之一,因为它是不需要的额外步骤。

  5. 要在 tkinter 中管理定时循环,我们可以使用after()

尝试这个:

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