Python QTimer的怪异行为

Python QTimer的怪异行为,python,pyqt,qtimer,Python,Pyqt,Qtimer,我有以下功能,每1秒使用QTimer更新我的计数器: def somefunc(): if self.pushButton_13.text() == 'OFF': self.pushButton_13.setText('ON') timer1.setInterval(1000) #timer1 is global variable timer1.timeout.connect(lambda: self.counter(

我有以下功能,每
1
秒使用
QTimer
更新我的
计数器

def somefunc(): 
  if self.pushButton_13.text() == 'OFF':
            self.pushButton_13.setText('ON')
            timer1.setInterval(1000) #timer1 is global variable
            timer1.timeout.connect(lambda: self.counter(15))
            timer1.start()
  else:
            self.pushButton_13.setText('OFF')
            timer1.stop()
            print timer1.timerId()

def counter(self, var):
    if var == 15:
        count = int(str(self.lineEdit_15.text()))

        count = count + 1
        print count
        self.lineEdit_15.setText(QtCore.QString(str(count)))

当我第一次按下按钮时,
计数器
工作正常,但如果再次单击按钮停止计时器,然后再次重新启动,计数器值每
1
秒更新一次,而应通过
1
更新一次。类似地,如果我再次单击按钮停止计数器并再次重新启动,则计数器将通过
3
进行更新,依此类推。我在哪里出错?

每次按下按钮都会建立一个新的连接,该连接独立于以前的连接。这会导致多次调用
计数器
插槽,每次连接调用一次。从Qt的:

您建立的每个连接都会发出一个信号,因此重复连接会发出两个信号。可以使用disconnect()断开连接

您应该只设置一次计时器(即创建计时器并将其连接到相应的插槽),然后根据需要多次启动计时器

或者,代码的最简单解决方案是:

        #...
        timer1.setInterval(1000)  
        timer1.disconnect()       # removes previous connections
        timer1.timeout.connect(lambda: self.counter(15))
        timer1.start()
        #...