gpt4 book ai didi

python - 如何用Qt设计倒计时

转载 作者:行者123 更新时间:2023-11-30 22:44:10 25 4
gpt4 key购买 nike

下面的代码创建一个QLabel并开始倒计时。每秒打印当前时间和剩余秒数。

enter image description here

除了打印当前时间(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):

enter image description here

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() 添加到“剩余时间”中:

 ...
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")))
...

enter image description here

关于python - 如何用Qt设计倒计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41604982/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com