Learning by doing: Reading books and trying to understand the (code) examples
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

88 lines
2.5 KiB

  1. import sys
  2. import pickle
  3. from notebook import Notebook, Note
  4. class Menu:
  5. '''Display a menu and respond to choices when run.'''
  6. def __init__(self):
  7. self.picklefile = 'notebook.pickle'
  8. self.notebook = Notebook()
  9. self.choices = {
  10. "1": self.show_notes,
  11. "2": self.search_notes,
  12. "3": self.add_note,
  13. "4": self.modify_note,
  14. "5": self.load_notes,
  15. "6": self.save_notes,
  16. "7": self.quit
  17. }
  18. def display_menu(self):
  19. print("""
  20. Notebook Menu
  21. 1. Show all Notes
  22. 2. Search Notes
  23. 3. Add Note
  24. 4. Modify Note
  25. 5. Load Notes
  26. 6. Save Notes
  27. 7. Quit """)
  28. def run(self):
  29. '''Display the menu and respond to choices.'''
  30. while True:
  31. self.display_menu()
  32. choice = input("Enter an option: ")
  33. action = self.choices.get(choice)
  34. if action:
  35. action()
  36. else:
  37. print("{0} is not a valid choice".format(choice))
  38. def show_notes(self, notes=None):
  39. if not notes:
  40. notes = self.notebook.notes
  41. for note in notes:
  42. print("{0}: {1}\n{2}".format(note.id, note.tags, note.memo))
  43. def search_notes(self):
  44. filter = input("Search for: ")
  45. notes = self.notebook.search(filter)
  46. self.show_notes(notes)
  47. def add_note(self):
  48. memo = input("Enter a memo: ")
  49. self.notebook.new_note(memo)
  50. print("Your note has been added.")
  51. def modify_note(self):
  52. id = input("Enter a note id: ")
  53. memo = input("Enter a memo: ")
  54. tags = input("Enter tags: ")
  55. if memo:
  56. if not self.notebook.modify_memo(id, memo):
  57. print("Note with id {0} doesn't exist.".format(id))
  58. if tags:
  59. if not self.notebook.modify_tags(id, tags):
  60. print("Note with id {0} doesn't exist.".format(id))
  61. def load_notes(self):
  62. with open(self.picklefile, 'rb') as f:
  63. # The protocol version used is detected automatically, so we do not
  64. # have to specify it.
  65. self.notebook = pickle.load(f)
  66. def save_notes(self):
  67. with open(self.picklefile, 'wb') as f:
  68. # Pickle the 'data' dictionary using the highest protocol available.
  69. pickle.dump(self.notebook, f, pickle.HIGHEST_PROTOCOL)
  70. def quit(self):
  71. print("Thank you for using your notebook today.")
  72. sys.exit(0)
  73. if __name__ == "__main__":
  74. Menu().run()