如何用Qt设计倒计时
How to design countdown with Qt
下面的代码创建一个 QLabel
并开始倒计时。它每秒打印一个当前时间和剩余秒数。
除了打印当前时间(Time now)之外,我还想打印倒计时结束时的时间。因此,生成的消息将如下所示:
"Time now: 20:00:01. Countdown ends at: 20:00:16"
如何实现?
import datetime
from PyQt4 import QtGui, QtCore
app = QtGui.QApplication([])
label = QtGui.QLabel()
label.resize(360, 40)
label.show()
count = 15
def countdown():
global count
if count < 1:
count = 15
label.setText( 'Time now: %s. Seconds left: %s'%(datetime.datetime.now().strftime("%H:%M:%S"), count))
count = count - 1
timer = QtCore.QTimer()
timer.timeout.connect(countdown)
timer.start(1000)
app.exec_()
工作解决方案:
(感谢 eyllanesc):
import datetime
from PyQt4 import QtGui, QtCore
app = QtGui.QApplication([])
label = QtGui.QLabel()
label.resize(360, 40)
label.show()
count = 15
def countdown():
global count
if count < 1:
count = 15
now = datetime.datetime.now()
label.setText( 'Time now: %s. End time: %s. Seconds left: %s'%(now.strftime("%H:%M:%S"), (now + datetime.timedelta(seconds=count)).strftime("%H:%M:%S"), count))
count = count - 1
interval = 1200
timer = QtCore.QTimer()
timer.timeout.connect(countdown)
timer.start(1000)
app.exec_()
您应该将 datetime.timedelta()
添加到 "remaining time":
...
now = datetime.datetime.now()
end = now + datetime.timedelta(seconds=count)
label.setText('Time now: %s. Countdown ends at: %s' % (now.strftime("%H:%M:%S"), end.strftime("%H:%M:%S")))
...
下面的代码创建一个 QLabel
并开始倒计时。它每秒打印一个当前时间和剩余秒数。
除了打印当前时间(Time now)之外,我还想打印倒计时结束时的时间。因此,生成的消息将如下所示:
"Time now: 20:00:01. Countdown ends at: 20:00:16"
如何实现?
import datetime
from PyQt4 import QtGui, QtCore
app = QtGui.QApplication([])
label = QtGui.QLabel()
label.resize(360, 40)
label.show()
count = 15
def countdown():
global count
if count < 1:
count = 15
label.setText( 'Time now: %s. Seconds left: %s'%(datetime.datetime.now().strftime("%H:%M:%S"), count))
count = count - 1
timer = QtCore.QTimer()
timer.timeout.connect(countdown)
timer.start(1000)
app.exec_()
工作解决方案:
(感谢 eyllanesc):
import datetime
from PyQt4 import QtGui, QtCore
app = QtGui.QApplication([])
label = QtGui.QLabel()
label.resize(360, 40)
label.show()
count = 15
def countdown():
global count
if count < 1:
count = 15
now = datetime.datetime.now()
label.setText( 'Time now: %s. End time: %s. Seconds left: %s'%(now.strftime("%H:%M:%S"), (now + datetime.timedelta(seconds=count)).strftime("%H:%M:%S"), count))
count = count - 1
interval = 1200
timer = QtCore.QTimer()
timer.timeout.connect(countdown)
timer.start(1000)
app.exec_()
您应该将 datetime.timedelta()
添加到 "remaining time":
...
now = datetime.datetime.now()
end = now + datetime.timedelta(seconds=count)
label.setText('Time now: %s. Countdown ends at: %s' % (now.strftime("%H:%M:%S"), end.strftime("%H:%M:%S")))
...