我读到一个倒计时计时器可以随着时间而定。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()
所以我们可以做一些事情来改善这一点
我们可以使用
strftime
来格式化超时,而不是使用if语句来管理格式。这可以做几天,几小时,几分钟,几秒钟等等,但现在我们只需要几秒钟您希望在与tkinter处于同一线程中时避免
while
和sleep()
。这是因为这两种方法将阻止主循环,因此您永远不会看到显示的时间,只有在while循环和sleep完成后才会看到GAME OVER
,因为它们都阻止了主循环在新行上编写导入,并使用
import tkinter as tk
而不是*
。这将有助于防止覆盖任何内容我们可以删除您的一个函数,因为这是一个不需要的额外步骤
要管理tkinter中的定时循环,我们可以使用
after()
试试这个:
相关问题 更多 >
编程相关推荐