我正在尝试在 python
中做一个时间计数器使用QTime
并在 QLabel
中显示这次使用PyQt
。我需要这样做,以显示 self 的程序开始工作以来已经过去了多少时间,使用这种时间格式:00:00:00
。我阅读了 QTime
的文档并尝试了我在互联网上搜索的另一个代码,但我无法使其工作。
这是我的代码的一部分:
class MyApplication(QtGui.QApplication):
def __init__(self, *args, **kwargs):
super(MyApplication, self).__init__(*args, **kwargs)
self.t = QTime() #I start QTime at the same time
self.t.start() # the program starts.
self.label_1 = QtGui.QLabel("Time since the program started:")
self.time_label = QtGui.QLabel("00:00:00")
self.tmr = QTimer() #I use QTimer because I need it
#for another part of the code
self.tmr.timeout.connect(self.clock)
def clock(self):
self.m = 0
self.elapsed = self.t.elapsed()
self.s = int((self.elapsed)/1000)
if self.s == 60:
self.m += 1
self.s = 0
self.time_sec = str(self.s)
self.time_min = str(self.m)
self.time = self.time_min + ":" + self.time_sec
self.time_label.setText(self.time) #I show the time in this QLabel()
当我构建这个时,我得到了这种时间格式:0:0
60 秒后(显示秒数)我得到这个结果:1:0
,并且没有其他事情发生。
如何使用以下格式制作我需要的计时器:00:00:00
。我可以使用 QTimer
来做到这一点吗? ?希望你能帮助我。
-----编辑------
感谢@amicitas和@linusg的回答,我已经尝试过datetime
模块,并编写了这个简单的代码:
class MyApplication(QtGui.QApplication):
def __init__(self, *args, **kwargs):
super(MyApplication, self).__init__(*args, **kwargs)
self.t0 = datetime.now()
self.tmr = QTimer()
self.tmr.timeout.connect(self.clock)
def.clock(self):
self.t1 = datetime.now()
self.hour = self.t1.hour - self.t0.hour
self.minute = self.t1.minute - self.t0.minute
self.second = self.t1.second - self.t0.second
print self.hour, self.minute, self.second
但是,当我构建这个时,当计数器达到 45 秒时,它会从 45 变为 -15,并出现“1 分钟”。这是:
当达到 0:0:44
时,它变成0:1:-15
.
可能是什么问题?我怎样才能显示我需要的时间格式?这是00:00:00
。希望你能帮助我。
最佳答案
我为您编写并测试了以下代码:
from datetime import datetime
import time
if __name__== '__main__':
initTimeObj = datetime.now()
nullRef = datetime(initTimeObj.year, initTimeObj.month, initTimeObj.day, 0, 0, 0)
print("Initial time:")
print(str(initTimeObj.hour) + ':' + str(initTimeObj.minute) + ':' + str(initTimeObj.second))
print("")
while(True):
time.sleep(1)
myDiff = datetime.now() - initTimeObj
myTimeObj = nullRef + myDiff
print(str(myTimeObj.hour) + ':' + str(myTimeObj.minute) + ':' + str(myTimeObj.second))
# Now you get a counting as follows:
# 0:0:1
# 0:0:2
# 0:0:3
# ...
# 0:0:59
# 0:1:0
# 0:1:1
# 0:1:2
# ...
这段代码完全符合您的需要。它从 0:0:0
开始计数并继续这样做。如果您确实想要使用两位数格式,例如 00:00:00
,则可能需要进行更多调整。如果您愿意,我可以进一步研究。
希望这对您有所帮助。请告诉我它是否对您有用。
关于python - 我如何使用 QTime() 制作时间计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37239381/