python - 如何在 tkinter 中进行简单的倒计时?
问题描述
我正在几分钟内制作一个简单的倒数计时器。我似乎无法在文本标签中显示倒计时。有人能帮我吗?
import tkinter as tk
import time
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
print(timeformat, end='\r')
label.config(text=timeformat)
time.sleep(1)
t -= 1
root = tk.Tk()
label = tk.Label(root,text="Time")
label.pack()
button = tk.Button(root,text = "click here", command=countdown(60)).pack()
root.mainloop()
解决方案
首先,而不是使用这个
button = tk.Button(root,text = "click here", command=countdown(60)).pack()
您必须使用lambda
指定参数
button = tk.Button(root,text = "click here", command=lambda:countdown(60)).pack()
然后root
每次更新标签时都必须更新
def countdown(t):
while t:
mins, secs = divmod(t, 60)
timeformat = '{:02d}:{:02d}'.format(mins, secs)
print(timeformat, end='\r')
label.config(text=timeformat)
root.update() #This way your program will display the numbers.
time.sleep(1)
t -= 1
我还建议使用线程,以便在程序运行时能够使用其他按钮。
要求的代码:
import threading
import tkinter as tk
import time
import sys
runtime = 300 #In seconds, you can change this
class CountdownApp:
def __init__(self, runtime):
self.runtime = runtime
self._createApp()
self._packElements()
self._startApp()
def _createApp(self):
self.root = tk.Tk()
def _packElements(self):
self.label = tk.Label(self.root,text="Time")
self.label.pack()
self.button = tk.Button(self.root,text = "click here", command=self.startCounter)
self.button.pack()
def countdown(self):
self.t = self.runtime
self.button.config(state='disabled')
while self.t > -1:
self.mins, self.secs = divmod(self.t, 60)
self.timeformat = '{:02d}:{:02d}'.format(self.mins, self.secs)
self.label.config(text=self.timeformat)
self.root.update()
time.sleep(1)
self.t -= 1
self.label.config(text='Time')
self.root.update()
self.button.config(state='normal')
def startCounter(self):
threading.Thread(target=self.countdown).start()
def _startApp(self):
self.root.mainloop()
CountdownApp(runtime)
推荐阅读
- python - 尝试使用 KivyMD 和 Python 显示 PDF 文件
- python - 我的不和谐机器人是否可以将另一个机器人添加到其服务器?
- node.js - 引擎“节点”与此模块不兼容。预期版本 > 0.4.x < 0.9.0"。有“12.22.1”吗?如何解决这个问题
- rx-swift - RxSwift 如何根据先前的结果跳过地图?
- javascript - Plyr Speed 从上方打开 - 希望它从下方打开
- java - 如何从包含嵌套/复杂对象的 Map 创建 DOM 元素列表
- javascript - NextJS Link 没有呈现锚标记
- javascript - jsconfig.json 为托管源和测试文件设置?
- .net-core - 动态加载 netstandard 实现程序集
- r - 如何在闪亮中使用反应函数时检索复选框组的列名