如何使计时器显示秒数?

2024-04-24 13:05:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我读到一个倒计时计时器可以随着时间而定。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()

Tags: textimporttimeconfiguredefsleepsecstart
1条回答
网友
1楼 · 发布于 2024-04-24 13:05:03

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

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

  2. 您希望在与tkinter处于同一线程中时避免whilesleep()。这是因为这两种方法将阻止主循环,因此您永远不会看到显示的时间,只有在while循环和sleep完成后才会看到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()

相关问题 更多 >