这是一个非常基础的程序,但我只是想了解如何在GUI窗口中显示最终结果?现在,我只是打印它,以检查它是否正常工作。我只是不知道如何使用函数'counting‘中的结果变量,并将其放入initGUI函数中,并将其显示给用户。
下面是我的代码:
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
,还是有更好的解决方案?
发布于 2017-05-04 03:24:31
比方说,我不会使用QInputDialog,而是使用QLineEdit。我会将它写回到主小部件中的标签中。例如,像这样
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_())
https://stackoverflow.com/questions/43766460
复制相似问题