Advertisement
Guest User

Untitled

a guest
Feb 27th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.20 KB | None | 0 0
  1. import sys
  2. import csv
  3.  
  4. from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
  5. from PyQt5.QtGui import QPixmap
  6.  
  7. #ADD IMPORT STATEMENT FOR YOUR GENERATED UI.PY FILE HERE
  8. import worldCountriesLIB
  9.  
  10. #CHANGE THE SECOND PARAMETER HERE TO MATCH YOUR GENERATED UI.PY FILE
  11. class MyForm(QMainWindow, worldCountriesLIB.Ui_MainWindow):
  12.  
  13. # --- Variables that will be used throughout the program ---
  14. changesMade = False # Will keep track of changes made to prompt saving
  15. totalPopulation = 0 # Used in calculating the total population loaded from the text file
  16.  
  17. # DO NOT MODIFY THIS CODE
  18. def __init__(self, parent=None):
  19. super(MyForm, self).__init__(parent)
  20. self.setupUi(self)
  21. # END DO NOT MODIFY
  22.  
  23. # ADD SLOTS HERE
  24. self.actionLoadCountries.triggered.connect(self.loadCountries)
  25. self.actionExitProgram.triggered.connect(self.exitProgram)
  26. self.listWidgetCountry.currentRowChanged.connect(self.changeCountry)
  27. self.pushButtonPopulationUpdate.clicked.connect(self.updateCountryPopulation)
  28. self.radioButtonMiles.clicked.connect(self.showMilesDensity)
  29. self.radioButtonKilometers.clicked.connect(self.showKiloDensity)
  30. self.comboBoxArea.currentIndexChanged.connect(self.changeAreaDisplay)
  31.  
  32. self.frameCountryInfo.hide()
  33.  
  34. # ADD SLOT FUNCTIONS HERE
  35. # Triggered when country data is loaded in using the menu
  36. def loadCountries(self):
  37. self.loadCountriesFromFile()
  38. self.loadCountriesIntoWidget()
  39.  
  40. # Triggers when a user selects a country from the list
  41. def changeCountry(self, newIndex):
  42. countryName = self.countryList[newIndex][0].lower()
  43. flagImage = QPixmap("Flags\\" + countryName.replace(" ", "_"))
  44. populationPercent = (int(self.countryList[newIndex][1]) / self.totalPopulation) * 100
  45. self.frameCountryInfo.show()
  46. self.labelCountryName.setText(self.countryList[newIndex][0])
  47. self.lineEditPopulationValue.setText("{:,}".format(int(self.countryList[newIndex][1])))
  48. self.labelAreaValue.setText("{:,}".format(int(self.countryList[newIndex][2])))
  49. self.labelFlagDisplay.setPixmap(flagImage)
  50. self.labelPopulationPercentValue.setText("{:,}%".format(round(populationPercent, 4)))
  51. self.comboBoxArea.setCurrentIndex(0)
  52. self.updatePopulationDensity()
  53.  
  54.  
  55. # Triggers when the user selects exit from the menu
  56. def exitProgram(self):
  57. # Will check if changes have been made to prompt user to save to file
  58. if self.changesMade:
  59. saveChanges = QMessageBox.question(self, "Save Changes?",
  60. "There are unsaved changes, would you like to save before exiting?",
  61. QMessageBox.Yes, QMessageBox.No)
  62. if saveChanges == QMessageBox.Yes:
  63. self.saveChangesToFile()
  64. QApplication.closeAllWindows()
  65.  
  66. # Triggers when the update button is clicked
  67. def updateCountryPopulation(self):
  68. self.saveChangesToMemory()
  69. self.changesMade = True # Flags that a change has been made
  70.  
  71. # Triggers when a new country is selected
  72. def updatePopulationDensity(self):
  73. if self.radioButtonMiles.isChecked() == True: # Checking radio buttons for correct display
  74. self.showMilesDensity()
  75. elif self.radioButtonKilometers.isChecked() == True: # Checking radio buttons for correct display
  76. self.showKiloDensity()
  77.  
  78. # Triggers when a country is selected
  79. # Defaults to square miles
  80. def changeAreaDisplay(self, newIndex):
  81. currentRow = self.listWidgetCountry.currentRow()
  82. if newIndex == 0: # Checking combo box for correct display
  83. countryArea = int(self.countryList[currentRow][2])
  84. elif newIndex == 1: # Checking combo box for correct display
  85. countryArea = int(int(self.countryList[currentRow][2]) * 2.58999)
  86. self.labelAreaValue.setText("{:,}".format(countryArea))
  87.  
  88. #ADD HELPER FUNCTIONS HERE
  89. # Used to read data from the text file
  90. def loadCountriesFromFile(self):
  91. fileName = "countries.txt"
  92. accessMode = "r"
  93. with open(fileName, accessMode) as countryFile:
  94. countryData = csv.reader(countryFile)
  95.  
  96. self.countryList = []
  97. for item in countryData:
  98. self.countryList.append(item)
  99.  
  100. # Populates the list widget from the data collected from the text file
  101. def loadCountriesIntoWidget(self):
  102. self.listWidgetCountry.clear()
  103. for country in self.countryList:
  104. self.listWidgetCountry.addItem(country[0])
  105. self.calculateTotalPopulation()
  106.  
  107. # Saves user inputted data to memory only
  108. def saveChangesToMemory(self):
  109. currentRow = self.listWidgetCountry.currentRow()
  110. # --- Error checking ---
  111. # User must enter a value
  112. # Value entered must be an integer value(or converted to an integer) before saving
  113. try:
  114. updatedPopulation = self.lineEditPopulationValue.text().replace(",", "")
  115. if updatedPopulation == "":
  116. QMessageBox.information(self, "Error", "Please enter a value before updating.", QMessageBox.Ok)
  117. else:
  118. self.countryList[currentRow][1] = int(updatedPopulation)
  119. QMessageBox.information(self, "Message", "Population Updated", QMessageBox.Ok)
  120. except ValueError:
  121. QMessageBox.information(self, "Error", "Invalid entry for population total.", QMessageBox.Ok)
  122. self.loadCountriesIntoWidget()
  123. self.listWidgetCountry.setCurrentRow(currentRow)
  124.  
  125. # Runs when country data is loaded into the widget
  126. def calculateTotalPopulation(self):
  127. self.totalPopulation = 0
  128. for row in self.countryList:
  129. self.totalPopulation += int(row[1])
  130.  
  131. # Saves user inputted data to the text file
  132. def saveChangesToFile(self):
  133. fileName = "countries.txt"
  134. accessMode = "w"
  135. with open(fileName, accessMode) as newCountryFile:
  136. for row in self.countryList:
  137. newCountryFile.write(",".join(row) + "\n")
  138. self.changesMade = False # Flags that any changes made have been saved
  139. QMessageBox.information(self, "Data Saved", "Your changes have been saved.", QMessageBox.Ok)
  140.  
  141. # Triggers when the radio button is clicked
  142. def showMilesDensity(self):
  143. currentRow = self.listWidgetCountry.currentRow()
  144. currentPopulation = int(self.countryList[currentRow][1])
  145. currentArea = int(self.countryList[currentRow][2])
  146. self.labelPopulationDensityValue.setText(str(round(currentPopulation / currentArea, 4)))
  147.  
  148. # Triggers when the radio button is clicked
  149. def showKiloDensity(self):
  150. currentRow = self.listWidgetCountry.currentRow()
  151. currentPopulation = int(self.countryList[currentRow][1])
  152. currentArea = int(self.countryList[currentRow][2]) * 2.58999
  153. self.labelPopulationDensityValue.setText(str(round(currentPopulation / currentArea, 4)))
  154.  
  155. # DO NOT MODIFY THIS CODE
  156. if __name__ == "__main__":
  157. app = QApplication(sys.argv)
  158. the_form = MyForm()
  159. the_form.show()
  160. sys.exit(app.exec_())
  161. # END DO NOT MODIFY
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement