This is a very basic program but I just want to understand how to display final result in GUI window? Now I am just printing it to check if its even works. I just don't know how to use result variable from function 'counting' and put it in initGUI function and display it to the user.
Here is my code:
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_())`
Any advice? Should I use QInputDialog
here or there is a better solution?
I would not use QInputDialog but rather, say, QLineEdit. I would write it back into a label in the main widget. Like that for instance
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_())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.