Making It Do Something…

keep-calm-and-do-something-39

Introduction

So far our work with PySide has been mostly demonstrative, meaning you’ve only watched code work.  You have yet to create something on your own that does something.

That changes today, sort of.

The code below allows the user to type two numbers in, press a button, and see the sum displayed in a label. Review the code, enter it in Geany, and run it to see how it works. Then see your assignment below.

import sys
from PySide import QtGui

# **************************************************
# Class Definition for GUI
# **************************************************
class AddWindow(QtGui.QWidget):
    
	# **************************************************
	def __init__(self):
		super(AddWindow, self).__init__()
		self.initUI()
        
	# **************************************************
	def initUI(self):      
		# The code below adds labels and entry boxes to the window
		
		# This code creates two entry boxes to receive the numbers from the user
		self.firstentry = QtGui.QLineEdit(self)
		self.firstentry.move(20, 20)

		self.secondentry = QtGui.QLineEdit(self)
		self.secondentry.move(20, 60)

		# This code creates a label where our result will be displayed
		self.answerlabel = QtGui.QLabel('Answer', self)
		self.answerlabel.move(20, 100)		

		# This code makes a button and connects it to the funciton buttonClicked()
		self.btn = QtGui.QPushButton('Add', self)
		self.btn.move(20, 140)
		self.btn.clicked.connect(self.buttonClicked)

		# This code sets the properties of the main app window
		self.setGeometry(300, 300, 290, 180)
		self.setWindowTitle('Add Two Numbers')
		self.show()
        
	# **************************************************
	def buttonClicked(self):
	
		# This function handles the button click event
		number1 = float(self.firstentry.text())
		number2 = float(self.secondentry.text())
		
		result = number1 + number2
		
		self.answerlabel.setText(str(result))

 
# **************************************************
# Main Program Function and Entry Point
# Do Not Edit the code below       
# **************************************************

def main():
    
    app = QtGui.QApplication(sys.argv)
    mywin = AddWindow()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

Assignment

Once you’ve made the above code work, your assignment is to adapt the code so that it receives three numbers, multiplies them, and displays their product in a label.

Submit your code by the end of the day using this submission link. Use the filename yourname-pysidemultiply.py.

#GoCreek