Python 基于PyQt的GUI中的定时器

Python 基于PyQt的GUI中的定时器,python,python-2.7,pyqt,pyqt4,Python,Python 2.7,Pyqt,Pyqt4,一个接一个地同时运行计时器时,我遇到了一个问题。下一个计时器正在运行,上一个计时器停止,到达时间后,上一个计时器启动。下面列出了有问题的代码 import time from PyQt4 import QtCore, QtGui import sys try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _enco

一个接一个地同时运行计时器时,我遇到了一个问题。下一个计时器正在运行,上一个计时器停止,到达时间后,上一个计时器启动。下面列出了有问题的代码

import time
from PyQt4 import QtCore, QtGui
import sys


try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)



class Window(QtGui.QMainWindow):

    def __init__(self):

        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle("PyQT tuts!")
        self.setWindowIcon(QtGui.QIcon('pythonlogo.png'))
        self.home()


    def home(self):

        self.btn = QtGui.QPushButton(self)
        self.btn.setObjectName(_fromUtf8("pb"))
        self.btn.clicked.connect(self.timer)
        self.btn.setText("Timer1")
        self.btn.resize(65,25)
        self.btn.move(100,100)

        self.btn2 = QtGui.QPushButton(self)
        self.btn2.setObjectName(_fromUtf8("pb2"))
        self.btn2.clicked.connect(self.timer2)
        self.btn2.setText("Timer2")
        self.btn2.resize(65,25)
        self.btn2.move(100,150)

        self.btn3 = QtGui.QPushButton(self)
        self.btn3.setObjectName(_fromUtf8("pb3"))
        self.btn3.clicked.connect(self.timer3)
        self.btn3.setText("Timer3")
        self.btn3.resize(65,25)
        self.btn3.move(100,200)

        self.btn4 = QtGui.QPushButton(self)
        self.btn4.setObjectName(_fromUtf8("pb4"))
        self.btn4.clicked.connect(self.timer4)
        self.btn4.setText("Timer4")
        self.btn4.resize(65,25)
        self.btn4.move(100,250)


        self.show()


    def timer(self):

        # uin = input("enter the time : ")

        when_to_stop = 10 
        # abs(int(uin))

        while when_to_stop > 0:
            m, s = divmod(when_to_stop, 60)
            h, m = divmod(m, 60)
            time_left = str(h).zfill(2) + ":" + str(m).zfill(2) + ":" + str(s).zfill(2)

            # print(time_left+'\r')
            time.sleep(1.0)
            when_to_stop -= 1
            self.btn.setText(str(time_left))
            QtGui.qApp.processEvents()


    def timer2(self):

        # uin = input("enter the time : ")

        when_to_stop = 10 
        # abs(int(uin))

        while when_to_stop > 0:
            m, s = divmod(when_to_stop, 60)
            h, m = divmod(m, 60)
            time_left = str(h).zfill(2) + ":" + str(m).zfill(2) + ":" + str(s).zfill(2)

            # print(time_left+'\r')
            time.sleep(1.0)
            when_to_stop -= 1
            self.btn2.setText(str(time_left))
            QtGui.qApp.processEvents()


    def timer3(self):

        # uin = input("enter the time : ")

        when_to_stop = 10
        # abs(int(uin))

        while when_to_stop > 0:
            m, s = divmod(when_to_stop, 60)
            h, m = divmod(m, 60)
            time_left = str(h).zfill(2) + ":" + str(m).zfill(2) + ":" + str(s).zfill(2)

            # print(time_left+'\r')
            time.sleep(1.0)
            when_to_stop -= 1
            self.btn3.setText(str(time_left))
            QtGui.qApp.processEvents()



     def timer4(self):

        # uin = input("enter the time : ")

        when_to_stop = 10 
        # abs(int(uin))

        while when_to_stop > 0:
            m, s = divmod(when_to_stop, 60)
            h, m = divmod(m, 60)
            time_left = str(h).zfill(2) + ":" + str(m).zfill(2) + ":" + str(s).zfill(2)

            # print(time_left+'\r')
            time.sleep(1.0)
            when_to_stop -= 1
            self.btn4.setText(str(time_left))
            QtGui.qApp.processEvents()




def run():


    app = QtGui.QApplication(sys.argv)
    GUI = Window()
    sys.exit(app.exec_())


run()

<代码>时间>睡眠()>代码>不应在GUI中使用,因为它会阻塞GUI EntError循环,导致不更新GUI的问题,除了使用输入()之外,还考虑不好的实践调用<代码> PraseServices()/<代码> .< Qt提供了QTimer,它是一个专门用于每隔一定时间间隔调用特定任务的类

在下一部分中,我将展示一个示例:

import sys
from PyQt4 import QtCore, QtGui
from functools import partial


class Window(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        centralwidget = QtGui.QWidget()
        self.setCentralWidget(centralwidget)
        layout = QtGui.QVBoxLayout(centralwidget)

        for i in range(4):
            button = QtGui.QPushButton("Timer{}".format(i+1))
            layout.addWidget(button)
            button.clicked.connect(partial(self.onClicked, button))

    def onClicked(self, button):
        sec = 10 # seconds
        timer =  button.property("timer").toPyObject()
        if timer is None:
            timer = QtCore.QTimer(button)
        timer.stop()
        timer.setInterval(1000)
        timer.setProperty("button", button)
        timer.setProperty("endTime", QtCore.QTime.currentTime().addMSecs(sec*1000+10))
        timer.timeout.connect(partial(self.onTimeout, timer))
        self.onTimeout(timer)
        timer.start()
        button.setProperty("timer", timer)

    def onTimeout(self, timer):
        button= timer.property("button")
        if hasattr(button, 'toPyObject'):
            button = button.toPyObject()
        tm = timer.property("endTime").toPyObject()
        if hasattr(tm, 'toPyObject'):
            tm = tm.toPyObject()
        ms = QtCore.QTime.currentTime().msecsTo(tm)
        if ms < 0:
            timer.stop()
        else:
            button.setText(QtCore.QTime().addMSecs(ms).toString())


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    ex = Window()
    ex.show()
    sys.exit(app.exec_())
导入系统 从PyQt4导入QtCore、QtGui 从functools导入部分 类窗口(QtGui.QMainWindow): def uuu init uuu(self,parent=None): 超级(窗口,自我)。\uuuuu初始化\uuuuuuu(父级) centralwidget=QtGui.QWidget() self.setCentralWidget(centralwidget) layout=QtGui.QVBoxLayout(centralwidget) 对于范围(4)中的i: button=QtGui.QPushButton(“计时器{}”.format(i+1)) layout.addWidget(按钮) 按钮。单击。连接(部分(自单击,按钮)) def onClicked(自身,按钮): 秒=10秒 timer=button.property(“timer”).toPyObject() 如果计时器为“无”: 定时器=QtCore.QTimer(按钮) 计时器停止() 定时器设置间隔(1000) timer.setProperty(“按钮”,按钮) timer.setProperty(“endTime”,QtCore.QTime.currentTime().addMSecs(秒*1000+10)) timer.timeout.connect(部分(self.onTimeout,timer)) 自动超时(计时器) timer.start() button.setProperty(“计时器”,计时器) def onTimeout(自身、计时器): button=timer.property(“按钮”) 如果hasattr(按钮“toPyObject”): button=button.toPyObject() tm=timer.property(“endTime”).toPyObject() 如果hasattr(tm,“toPyObject”): tm=tm.toPyObject() ms=QtCore.QTime.currentTime().msecsTo(tm) 如果ms<0: 计时器停止() 其他: button.setText(QtCore.QTime().addMSecs(ms.toString()) 如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu': app=QtGui.QApplication(sys.argv) ex=窗口() 例如:show() sys.exit(app.exec_())
谢谢您的回复,先生,但是计时器没有在屏幕上显示任何值button@amanrawat您是否尝试过我的代码,或者是否已将其改编为初始代码?您按下按钮了吗?是的,先生,我修改了您的代码并按下了按钮,但仍然没有在按钮上显示计时器值。@AmanRaw首先尝试我的原始代码,如果它有效,问题在于您的修改,而不是我的答案。告诉我我的示例是否有效。@amanrawat好吧,它对我来说正确,python和pyqt4的版本是什么?