如何将QLineEdit值传递给另一个函数?

时间:2016-09-13 15:04:25

标签: python pyqt pyqt4

我使用的是Python 2.7和PyQT4,我正在制作一个简单的计算器,我有两个QLineEdit,我有一个打印添加结果的函数。

class Window(QtGui.QMainWindow):
    global number_1_text
    global number_2_text

    def __init__(self):
        super(Window, self).__init__()
        self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint)
        #Main Window Settings
        self.setGeometry(50,50,500,300)
        self.setWindowTitle("Point of sale !")
        self.setWindowIcon(QtGui.QIcon('python.png'))

        #Close Action
        exitAction = QtGui.QAction(QtGui.QIcon('python.png'),"Close Now !", self)
        exitAction.setShortcut("Ctrl+Q")
        exitAction.setStatusTip('Leave the Application')
        exitAction.triggered.connect(self.close_application)
        self.statusBar()

        #Menubar
        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu('&File')
        fileMenu.addAction(exitAction)


        # Create textboxs
        number_1 = QtGui.QLineEdit(self)
        number_1.move(20, 50)
        number_1.resize(380,40)
        self.number_1_text = number_1.text()

        number_2 = QtGui.QLineEdit(self)
        number_2.move(20, 100)
        number_2.resize(380,40)
        self.number_2_text = number_2.text()

        #Main Home Proccess
        quiteBtn = QtGui.QPushButton("Quite", self)
        quiteBtn.resize(100, 50)
        quiteBtn.move(50,220)
        quiteBtn.clicked.connect(self.close_application)

        addBtn = QtGui.QPushButton("Add", self)
        addBtn.resize(100, 50)
        addBtn.move(150,220)
        addBtn.clicked.connect(self.addNumbers)
        self.show()

    def addNumbers(self):
        print self.number_1_text
        print self.number_2_text
        print "Done"

    #Close The Whole Application
    def close_application(self):
        choice = QtGui.QMessageBox.question(self, 'Exit !', 'Are you sure you wanna exit?',
            QtGui.QMessageBox.Yes | QtGui.QMessageBox.No
            )
        if choice == QtGui.QMessageBox.Yes:
            sys.exit()
        else:
            pass

我尝试使用text()函数获取值并将其分配给类中的全局变量,然后我尝试调用addNumbers函数中的值,但我得到一个空值。

结果的屏幕截图: Result

1 个答案:

答案 0 :(得分:1)

您应该创建主窗口的子窗口小部件属性。这样,您可以在以后轻松访问它们:

class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        ...
        self.number_1 = QtGui.QLineEdit(self)
        self.number_1.move(20, 50)
        self.number_1.resize(380, 40)

        self.number_2 = QtGui.QLineEdit(self)
        self.number_2.move(20, 100)
        self.number_2.resize(380, 40)
        ...

    def addNumbers(self):
        a = float(self.number_1.text())
        b = float(self.number_2.text())
        print '%s + %s = %s' % (a, b, a + b)
        print 'Done'