python - 如何用Qt设计倒计时

标签 python qt pyqt pyqt4 qtimer

下面的代码创建一个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/

相关文章:

python - "django.db.utils.ProgrammingError: relation "app_user "does not exist"在 manage.py 测试期间

c++ - 带变量的 SQL 查询

c++ - Qt 多边形的线性渐变

python - py安装程序: qwebkit cannot load pictures and garbled text when package pyside gui with pyinstaller

python - 有没有办法检查字符串是否是 django 查询集的有效过滤器?

python - 如何为 python kivy 绘画应用程序添加一个清除按钮

python - 在 SQLAlchemy 中,如何在 GROUP BY 之后对算术表达式进行 ORDER BY?

c++ - Qt Web 引擎获取历史记录

python - PyQt5:如何为每个角色设置自定义鼠标指针?

python - 属性错误 : 'Ui_MainWindow' object has no attribute 'setCentralWidget'