首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >PyQt5 -非常基础

PyQt5 -非常基础
EN

Stack Overflow用户
提问于 2017-05-04 01:25:25
回答 1查看 91关注 0票数 1

这是一个非常基础的程序,但我只是想了解如何在GUI窗口中显示最终结果?现在,我只是打印它,以检查它是否正常工作。我只是不知道如何使用函数'counting‘中的结果变量,并将其放入initGUI函数中,并将其显示给用户。

下面是我的代码:

代码语言:javascript
运行
复制
import sys
from PyQt5.QtWidgets import QWidget, QApplication,  QPushButton, QHBoxLayout, QInputDialog


class Calculator(QWidget):

    def __init__(self):
        super().__init__()

        self.initGUI()


    def initGUI(self):

        self.setGeometry(300, 300, 400, 300)
        self.setWindowTitle('Calculator')
        self.show()

        layout = QHBoxLayout(self)

        adding = QPushButton('Adding', self)
        adding.clicked.connect(self.counting)

        layout.addWidget(adding)

        self.setLayout(layout)

    def counting(self):

        num1, ok=QInputDialog.getInt(None, 'Type first value', 'here')
        num2, ok=QInputDialog.getInt(None, 'Type second value', 'here')
        result = num1 + num2
        print(result)



if __name__=='__main__':
    app = QApplication(sys.argv)
    ex = Calculator()
    sys.exit(app.exec_())`

有什么建议吗?我应该在这里使用QInputDialog,还是有更好的解决方案?

EN

回答 1

Stack Overflow用户

发布于 2017-05-04 03:24:31

比方说,我不会使用QInputDialog,而是使用QLineEdit。我会将它写回到主小部件中的标签中。例如,像这样

代码语言:javascript
运行
复制
import sys
from PyQt5.QtWidgets import *

class Calculator(QWidget):
    first = 0
    second = 0

    def __init__(self, parent=None):
        super(Calculator, self).__init__(parent)

        self.setGeometry(300, 300, 400, 300)
        self.setWindowTitle('Calculator')

        layout = QHBoxLayout(self)

        firstButton = QPushButton('Get first', self)
        firstButton.clicked.connect(self.get_first)

        secondButton = QPushButton('Get Second', self)
        secondButton.clicked.connect(self.get_second)

        thirdButton = QPushButton('Get Both', self)
        thirdButton.clicked.connect(self.get_both)

        layout.addWidget(firstButton )
        layout.addWidget(secondButton)
        layout.addWidget(thirdButton)

        self.resultLabel = QLabel()
        layout.addWidget(self.resultLabel)

        self.setLayout(layout)

    def get_first(self):
        num1, ok=QInputDialog.getInt(self, 'Type first value', 'here')
        if ok and num1:
            self.first = num1
        self.resultLabel.setText(str(self.first+self.second))

    def get_second(self):
        num2, ok = QInputDialog.getInt(self, 'Type second value', 'here')
        if ok and num2:
            self.second = num2
        self.resultLabel.setText(str(self.first + self.second))

    def get_both(self):
        self.get_first()
        self.get_second()

if __name__=='__main__':
    app = QApplication(sys.argv)
    ex = Calculator()
    ex.show()
    sys.exit(app.exec_())
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43766460

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档