简体   繁体   中英

How can I make a timer display seconds?

I read that a countdown timer could be made with time.sleep(). This is my attempt. I can print the seconds to the idle, but not to the Tkinter window. 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. 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. 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.

  3. Write your imports on new lines and use import tkinter as tk instead of * . 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() .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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