【问题标题】:how to display a message with two buttons in python qt designer如何在python qt设计器中显示带有两个按钮的消息
【发布时间】:2020-07-31 16:00:22
【问题描述】:

我正在构建一个小型扫雷克隆,我在这里有一个功能,用于用户单击炸弹按钮显示“boom”的事件,但我还想添加一个功能,其中弹出菜单之类的提示提示用户,并为他们提供两个按钮,一个继续,另一个要求开始新游戏。

def buttonClickedkill(self):
    # sender() tells us who caused the action to take place
    clicked = self.sender()
    #letter=clicked.text()  # the buttons have the letters on them
    #print(f"Button -{letter}- was clicked!")
    # 1) Disable the button
    clicked.setEnabled(False)
    clicked.setText("boom")
    QMainWindow.__init__(self)

所以我想添加另一个功能,其中弹出的东西会说:

对不起,你击中炸弹死了!

继续?新游戏!

“继续”和“新游戏”是两个按钮 我有一个新的游戏功能和所有。

您能否向我提供必要的脚本,以便在单击其中一个按钮后立即关闭窗口?

【问题讨论】:

    标签: python qt pyqt5 designer


    【解决方案1】:

    这是QMessageBox 的确切用例。例如:

    reply = QMessageBox.question(self, 'Title', 'You lost! Continue?')
    

    这一行会弹出一个窗口并阻止主 GUI,直到用户单击按钮。因为我选择了QMessageBox.question,所以默认按钮是“是”和“否”。您可以询问reply 变量,用户点击的是“是”(QMessageBox.Yes)还是“否”(QMessageBox.No)按钮。

    工作示例:

    import sys
    
    from PyQt5.QtWidgets import (QApplication, QLabel, QMainWindow, 
                                 QMessageBox, QPushButton, QVBoxLayout, 
                                 QWidget)
    
    
    class MyApp(QMainWindow):
        def __init__(self):
            super().__init__()
            self.widget = QWidget(self)
            self.setCentralWidget(self.widget)
            layout = QVBoxLayout()
            self.widget.setLayout(layout)
    
            self.button = QPushButton(parent=self, text="Click Me!")
            self.button.clicked.connect(self.button_clicked_kill)
            self.text = QLabel(parent=self, text='')
    
            layout.addWidget(self.button)
            layout.addWidget(self.text)
    
        def button_clicked_kill(self):
            reply = QMessageBox.question(self, 'Title', 'You lost! Continue?')
            if reply == QMessageBox.Yes:
                self.text.setText('User answered yes')
            if reply == QMessageBox.No:
                self.text.setText('User answered no')
    
    
    if __name__ == '__main__':
        app = QApplication()
        gui = MyApp()
        gui.show()
        sys.exit(app.exec_())
    

    生成:

    【讨论】:

    • 我不知道你是怎么做到的,但我感激不尽!我被困了两个小时,已经在 Youtube 上观看了一堆印度视频,我什至构建并导入了一个不同的类,创建了几乎全新的设计和东西,我不敢相信有那么容易。非常感谢!
    • 很高兴我能帮上忙!请记住,大多数“常见”的 GUI 功能,如文本框、进度条、选项卡等,在 Qt 上都有某种现成的实现。当您遇到问题时,请尝试在(诚然令人困惑和不完整的)文档中深入挖掘。
    • @yesitsme 还考虑了原始的 C++ 文档,它比 pyside 的文档更全面、更易读;即使它是面向 C++ 的,在 99% 的情况下,函数名称、参数和返回的数据类型都是相同的,您可以从 pyside/pyqt 文档或在 python shell 中使用help() 检查是否存在不一致。最后,从研究基类(QObject/QWidget)开始,然后从那里读取每个继承的类(例如:查看所有继承自 QDialog 的类,而后者又继承自 QWidget)。
    • 再次感谢您,您的回答绝对专业。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-15
    • 2021-09-24
    • 2019-01-05
    • 1970-01-01
    相关资源
    最近更新 更多