在继续运行代码之前等待计时器终止 [英] Waiting for a timer to terminate before continuing running the code
问题描述
以下代码在按下 START
按钮后每秒更新一次按钮的文本.预期的功能是让代码等待"直到计时器停止,然后再继续执行代码.即按下START
后,第二个按钮的文字递增到3
,然后才会出现I wait!
文字在控制台上.
上面的代码挂起 GUI,如果我删除 while True:
循环,I waited!
会立即出现在控制台上.
我确定 while True:
循环不是正确的方法,所以我正在寻找建议.
我发现有效的解决方案是替换
虽然为真:如果不是 self.timer.isActive():休息
与
while self.timer.isActive():QtGui.QApplication.processEvents()
不过,我不确定这是最好的解决方案.
The following code updates the text of a button every second after the START
button was pressed. The intended functionality is for the code to 'wait' until the timer has stopped before continuing on with the execution of the code. That is, after START
is pressed, the text of the second button is incremented to 3
, and only then should the text I waited!
appear on the console.
import sys
from PySide import QtGui, QtCore
class Example(QtGui.QWidget):
def __init__(self, parent=None):
super(Example, self).__init__(parent)
self.app_layout = QtGui.QVBoxLayout()
self.setLayout(self.app_layout)
self.setGeometry(300, 300, 50, 50)
self.current_count = 0
self.count_to = 4
self.delay = 1000
self.timer = QtCore.QTimer(self)
self.timer.timeout.connect(self.updateButtonCount)
# start button
start_button = QtGui.QPushButton()
start_button.setText('START')
start_button.clicked.connect(self.startCount)
self.app_layout.addWidget(start_button)
# number button
self.number_button = QtGui.QPushButton()
self.number_button.setText('0')
self.app_layout.addWidget(self.number_button)
def updateButtonCount(self):
self.number_button.setText("%s" % self.current_count)
self.current_count += 1
if self.current_count == self.count_to:
self.timer.stop()
def startCount(self):
self.current_count = 0
self.timer.start(self.delay)
# this loop hangs the GUI:
while True:
if not self.timer.isActive():
break
print 'I waited!'
def main():
app = QtGui.QApplication(sys.argv)
example = Example()
example.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The above code hangs the GUI, and if I remove the while True:
loop, the I waited!
appears immidiately on the console.
I'm certain that the while True:
loop is not the correct way to go about it, so I'm looking for suggestions.
The solution I found that works was to replace
while True:
if not self.timer.isActive():
break
with
while self.timer.isActive():
QtGui.QApplication.processEvents()
I'm not certain that this is the best solution, though.
这篇关于在继续运行代码之前等待计时器终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!