2016-09-13 49 views
0

我正在使用Python 2.7和PyQT4,我正在做一个简单的计算器,我有两个QLineEdit,我有一个打印添加结果的函数。如何将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

回答

0

你应该让你的孩子部件主窗口的属性。这样一来,你可以很容易日后访问:

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' 
+0

我想你的解决方案 但我得到 回溯(最近通话最后一个): 文件“C:\用户\ LilEssam \桌面\ pos.py”第0行,在 class Window(QtGui.QMainWindow): 窗口中的第54行中的文件“C:\ Users \ LilEssam \ Desktop \ pos.py” b = float(self.number_2.text()) NameError:name'self'未定义 –

+0

@AhmedEssam。这是因为你没有在我的例子中使用代码 - 'addNumbers'必须是'Window'类的一个方法。 – ekhumoro

+0

谢谢队友!它现在正在工作,非常感谢! –

相关问题