2017-05-03 79 views
1

這是一個非常基本的程序,但我只是想了解如何在GUI窗口中顯示最終結果?現在我只是打印它來檢查它是否可以正常工作。我只是不知道如何使用函數'counting'中的結果變量並將其放入initGUI函數中並將其顯示給用戶。PyQt5 - 非常基礎

這裏是我的代碼:

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還是有更好的解決方案?

回答

0

我不會使用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_())