python - pyqt5中按下按钮有时间限制吗?

标签 python pyqt pyqt5

我正在做一个通过回答问题来扩散炸弹的游戏。有什么办法可以等待用户在某个时间按下按钮吗?当特定时间耗尽时,该按钮将被禁用。谢谢您的回答:)

最佳答案

您必须使用 QTimer 来实现逻辑:

from PyQt5 import QtCore, QtWidgets
from functools import partial

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        button = QtWidgets.QPushButton(
            text='Start Game',
            clicked=self.on_start_game_clicked
        )
        self.game_button = QtWidgets.QPushButton(
            text='Press me',
            clicked=self.on_game_clicked
        )
        self.time_label = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(button)
        lay.addWidget(self.game_button)
        lay.addWidget(self.time_label)

        self.timer = QtCore.QTimer(self, 
            interval=5000, # time in ms
            timeout=partial(self.game_button.setDisabled, True),
            singleShot=True
        )
        self.time_timer = QtCore.QTimer(self,
            interval=100,
            timeout=self.update_label
        )

    @QtCore.pyqtSlot()
    def on_start_game_clicked(self):
        if not self.timer.isActive():
            self.timer.start()
            self.time_timer.start()
            self.game_button.setEnabled(True)

    @QtCore.pyqtSlot()
    def update_label(self):
        if self.timer.remainingTime() >= 0:
            self.time_label.setText('{0:.2f} ms'.format(self.timer.remainingTime()*0.001))
        else:
            self.time_label.setText('0 ms')

    @QtCore.pyqtSlot()
    def on_game_clicked(self):
        print("clicked")


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

关于python - pyqt5中按下按钮有时间限制吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54918549/

相关文章:

python - PyQt4 QComboBox 信号和槽

python - 使用按键单击时如何更改pyqt5中的按钮文本

python - 内存不足,无法将 .mat 结果文件读入 Python

用于将 UTF-8 转换为 ASCII 的 Python 脚本

python - pyqt中GUI的模型 View 实现错误

python - 用钢笔在 Canvas 上删除

python - PyQt 5 : How to maintain relative widget size when expanding a window

python - 使用 QDesktopService 显示本地 html 文件

python - 在 Pyqt4 Python 中从 QtableWidget 中的 QlineEdit 检索值

python - 将 SQL 命令转换为 Python 的 ORM