簡體   English   中英

按下pyqt5中的按鈕有時間限制嗎?

[英]is there any time limit in pushing the push button in 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_())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM