Simple Contact List Using Python

In this tutorial we will create a Simple Contact List Using Python. Python is a widely used advance-level programming language for a general technique to the developer. Beginners find Python a clean syntax and indentation structure based, and it is easy to learn because of its less semi colon problem. So let do the coding. Getting started: First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/. Installing SQLite Browser After you installed Python, we will now then install the SQLite, here's the link for the DB Browser for SQLite http://sqlitebrowser.org/. Importing Modules After setting up the installation and the database, run the IDLE and click file and then new file. After that a new window will appear containing a black file this will be the text editor for the python. Then copy code that I provided below and paste it inside the IDLE text editor
  1. from tkinter import *
  2. import sqlite3
  3. import tkinter.ttk as ttk
  4. import tkinter.messagebox as tkMessageBox
Setting up the Main Frame After importing the modules, we will now then create the main frame for the application. To do that just copy the code below and paste it inside the IDLE text editor.
  1. root = Tk()
  2. root.title("Sourcecodester")
  3. width = 500
  4. height = 400
  5. screen_width = root.winfo_screenwidth()
  6. screen_height = root.winfo_screenheight()
  7. x = (screen_width/2) - (width/2)
  8. y = (screen_height/2) - (height/2)
  9. root.geometry("%dx%d+%d+%d" % (width, height, x, y))
  10. root.resizable(0, 0)
  11. root.config(bg="#6666ff")
Designing the Layout After creating the Main Frame we will now add some layout to the application. Just kindly copy the code below and paste it inside the IDLE text editor.
  1. #============================FRAMES======================================
  2. Top = Frame(root, width=500, bd=1, relief=SOLID)
  3. Top.pack(side=TOP)
  4. Mid = Frame(root, width=500, bg="#6666ff")
  5. Mid.pack(side=TOP)
  6. MidLeft = Frame(Mid, width=100)
  7. MidLeft.pack(side=LEFT, pady=10)
  8. MidLeftPadding = Frame(Mid, width=370, bg="#6666ff")
  9. MidLeftPadding.pack(side=LEFT)
  10. MidRight = Frame(Mid, width=100)
  11. MidRight.pack(side=RIGHT, pady=10)
  12. TableMargin = Frame(root, width=500)
  13. TableMargin.pack(side=TOP)
  14. #============================LABELS======================================
  15. lbl_title = Label(Top, text="Simple Contact List Using Python", font=('arial', 16), width=500)
  16. lbl_title.pack(fill=X)
  17.  
  18. #============================ENTRY=======================================
  19.  
  20. #============================BUTTONS=====================================
  21. btn_add = Button(MidLeft, text="+ ADD NEW", bg="#66ff66", command=AddNewWindow)
  22. btn_add.pack()
  23. btn_delete = Button(MidRight, text="DELETE", bg="red", command=DeleteData)
  24. btn_delete.pack(side=RIGHT)
  25.  
  26. #============================TABLES======================================
  27. scrollbarx = Scrollbar(TableMargin, orient=HORIZONTAL)
  28. scrollbary = Scrollbar(TableMargin, orient=VERTICAL)
  29. tree = ttk.Treeview(TableMargin, columns=("MemberID", "Firstname", "Lastname", "Gender", "Age", "Address", "Contact"), height=400, selectmode="extended", yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set)
  30. scrollbary.config(command=tree.yview)
  31. scrollbary.pack(side=RIGHT, fill=Y)
  32. scrollbarx.config(command=tree.xview)
  33. scrollbarx.pack(side=BOTTOM, fill=X)
  34. tree.heading('MemberID', text="MemberID", anchor=W)
  35. tree.heading('Firstname', text="Firstname", anchor=W)
  36. tree.heading('Lastname', text="Lastname", anchor=W)
  37. tree.heading('Gender', text="Gender", anchor=W)
  38. tree.heading('Age', text="Age", anchor=W)
  39. tree.heading('Address', text="Address", anchor=W)
  40. tree.heading('Contact', text="Contact", anchor=W)
  41. tree.column('#0', stretch=NO, minwidth=0, width=0)
  42. tree.column('#1', stretch=NO, minwidth=0, width=0)
  43. tree.column('#2', stretch=NO, minwidth=0, width=80)
  44. tree.column('#3', stretch=NO, minwidth=0, width=120)
  45. tree.column('#4', stretch=NO, minwidth=0, width=90)
  46. tree.column('#5', stretch=NO, minwidth=0, width=80)
  47. tree.column('#6', stretch=NO, minwidth=0, width=180)
  48. tree.column('#7', stretch=NO, minwidth=0, width=120)
  49. tree.pack()
  50. tree.bind('<Double-Button-1>', OnSelected)
Creating the Database Connection Then after setting up the design we will now create the database function. To do that just simply copy the code below and paste it inside the IDLE text editor.
  1. #============================METHODS=====================================
  2. def Database():
  3. conn = sqlite3.connect("pythontut.db")
  4. cursor = conn.cursor()
  5. cursor.execute("CREATE TABLE IF NOT EXISTS `member` (mem_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, firstname TEXT, lastname TEXT, gender TEXT, age TEXT, address TEXT, contact TEXT)")
  6. cursor.execute("SELECT * FROM `member` ORDER BY `lastname` ASC")
  7. fetch = cursor.fetchall()
  8. for data in fetch:
  9. tree.insert('', 'end', values=(data))
  10. cursor.close()
  11. conn.close()
Creating the Main Function This is where the code will generate and process the contact list of each individual. The admin can add, update, and delete the data of each individuals when the require field is attained.
  1. def SubmitData():
  2. if FIRSTNAME.get() == "" or LASTNAME.get() == "" or GENDER.get() == "" or AGE.get() == "" or ADDRESS.get() == "" or CONTACT.get() == "":
  3. result = tkMessageBox.showwarning('', 'Please Complete The Required Field', icon="warning")
  4. else:
  5. tree.delete(*tree.get_children())
  6. conn = sqlite3.connect("pythontut.db")
  7. cursor = conn.cursor()
  8. cursor.execute("INSERT INTO `member` (firstname, lastname, gender, age, address, contact) VALUES(?, ?, ?, ?, ?, ?)", (str(FIRSTNAME.get()), str(LASTNAME.get()), str(GENDER.get()), int(AGE.get()), str(ADDRESS.get()), str(CONTACT.get())))
  9. conn.commit()
  10. cursor.execute("SELECT * FROM `member` ORDER BY `lastname` ASC")
  11. fetch = cursor.fetchall()
  12. for data in fetch:
  13. tree.insert('', 'end', values=(data))
  14. cursor.close()
  15. conn.close()
  16. FIRSTNAME.set("")
  17. LASTNAME.set("")
  18. GENDER.set("")
  19. AGE.set("")
  20. ADDRESS.set("")
  21. CONTACT.set("")
  22.  
  23. def UpdateData():
  24. if GENDER.get() == "":
  25. result = tkMessageBox.showwarning('', 'Please Complete The Required Field', icon="warning")
  26. else:
  27. tree.delete(*tree.get_children())
  28. conn = sqlite3.connect("pythontut.db")
  29. cursor = conn.cursor()
  30. cursor.execute("UPDATE `member` SET `firstname` = ?, `lastname` = ?, `gender` =?, `age` = ?, `address` = ?, `contact` = ? WHERE `mem_id` = ?", (str(FIRSTNAME.get()), str(LASTNAME.get()), str(GENDER.get()), str(AGE.get()), str(ADDRESS.get()), str(CONTACT.get()), int(mem_id)))
  31. conn.commit()
  32. cursor.execute("SELECT * FROM `member` ORDER BY `lastname` ASC")
  33. fetch = cursor.fetchall()
  34. for data in fetch:
  35. tree.insert('', 'end', values=(data))
  36. cursor.close()
  37. conn.close()
  38. FIRSTNAME.set("")
  39. LASTNAME.set("")
  40. GENDER.set("")
  41. AGE.set("")
  42. ADDRESS.set("")
  43. CONTACT.set("")
  44.  
  45.  
  46. def OnSelected(event):
  47. global mem_id, UpdateWindow
  48. curItem = tree.focus()
  49. contents =(tree.item(curItem))
  50. selecteditem = contents['values']
  51. mem_id = selecteditem[0]
  52. FIRSTNAME.set("")
  53. LASTNAME.set("")
  54. GENDER.set("")
  55. AGE.set("")
  56. ADDRESS.set("")
  57. CONTACT.set("")
  58. FIRSTNAME.set(selecteditem[1])
  59. LASTNAME.set(selecteditem[2])
  60. AGE.set(selecteditem[4])
  61. ADDRESS.set(selecteditem[5])
  62. CONTACT.set(selecteditem[6])
  63. UpdateWindow = Toplevel()
  64. UpdateWindow.title("Sourcecodester")
  65. width = 400
  66. height = 300
  67. screen_width = root.winfo_screenwidth()
  68. screen_height = root.winfo_screenheight()
  69. x = ((screen_width/2) + 450) - (width/2)
  70. y = ((screen_height/2) + 20) - (height/2)
  71. UpdateWindow.resizable(0, 0)
  72. UpdateWindow.geometry("%dx%d+%d+%d" % (width, height, x, y))
  73. if 'NewWindow' in globals():
  74. NewWindow.destroy()
  75.  
  76. #===================FRAMES==============================
  77. FormTitle = Frame(UpdateWindow)
  78. FormTitle.pack(side=TOP)
  79. ContactForm = Frame(UpdateWindow)
  80. ContactForm.pack(side=TOP, pady=10)
  81. RadioGroup = Frame(ContactForm)
  82. Male = Radiobutton(RadioGroup, text="Male", variable=GENDER, value="Male", font=('arial', 14)).pack(side=LEFT)
  83. Female = Radiobutton(RadioGroup, text="Female", variable=GENDER, value="Female", font=('arial', 14)).pack(side=LEFT)
  84.  
  85. #===================LABELS==============================
  86. lbl_title = Label(FormTitle, text="Updating Contacts", font=('arial', 16), bg="orange", width = 300)
  87. lbl_title.pack(fill=X)
  88. lbl_firstname = Label(ContactForm, text="Firstname", font=('arial', 14), bd=5)
  89. lbl_firstname.grid(row=0, sticky=W)
  90. lbl_lastname = Label(ContactForm, text="Lastname", font=('arial', 14), bd=5)
  91. lbl_lastname.grid(row=1, sticky=W)
  92. lbl_gender = Label(ContactForm, text="Gender", font=('arial', 14), bd=5)
  93. lbl_gender.grid(row=2, sticky=W)
  94. lbl_age = Label(ContactForm, text="Age", font=('arial', 14), bd=5)
  95. lbl_age.grid(row=3, sticky=W)
  96. lbl_address = Label(ContactForm, text="Address", font=('arial', 14), bd=5)
  97. lbl_address.grid(row=4, sticky=W)
  98. lbl_contact = Label(ContactForm, text="Contact", font=('arial', 14), bd=5)
  99. lbl_contact.grid(row=5, sticky=W)
  100.  
  101. #===================ENTRY===============================
  102. firstname = Entry(ContactForm, textvariable=FIRSTNAME, font=('arial', 14))
  103. firstname.grid(row=0, column=1)
  104. lastname = Entry(ContactForm, textvariable=LASTNAME, font=('arial', 14))
  105. lastname.grid(row=1, column=1)
  106. RadioGroup.grid(row=2, column=1)
  107. age = Entry(ContactForm, textvariable=AGE, font=('arial', 14))
  108. age.grid(row=3, column=1)
  109. address = Entry(ContactForm, textvariable=ADDRESS, font=('arial', 14))
  110. address.grid(row=4, column=1)
  111. contact = Entry(ContactForm, textvariable=CONTACT, font=('arial', 14))
  112. contact.grid(row=5, column=1)
  113.  
  114.  
  115. #==================BUTTONS==============================
  116. btn_updatecon = Button(ContactForm, text="Update", width=50, command=UpdateData)
  117. btn_updatecon.grid(row=6, columnspan=2, pady=10)
  118.  
  119.  
  120.  
  121. def DeleteData():
  122. if not tree.selection():
  123. result = tkMessageBox.showwarning('', 'Please Select Something First!', icon="warning")
  124. else:
  125. result = tkMessageBox.askquestion('', 'Are you sure you want to delete this record?', icon="warning")
  126. if result == 'yes':
  127. curItem = tree.focus()
  128. contents =(tree.item(curItem))
  129. selecteditem = contents['values']
  130. tree.delete(curItem)
  131. conn = sqlite3.connect("pythontut.db")
  132. cursor = conn.cursor()
  133. cursor.execute("DELETE FROM `member` WHERE `mem_id` = %d" % selecteditem[0])
  134. conn.commit()
  135. cursor.close()
  136. conn.close()
  137.  
  138. def AddNewWindow():
  139. global NewWindow
  140. FIRSTNAME.set("")
  141. LASTNAME.set("")
  142. GENDER.set("")
  143. AGE.set("")
  144. ADDRESS.set("")
  145. CONTACT.set("")
  146. NewWindow = Toplevel()
  147. NewWindow.title("Sourcecodester")
  148. width = 400
  149. height = 300
  150. screen_width = root.winfo_screenwidth()
  151. screen_height = root.winfo_screenheight()
  152. x = ((screen_width/2) - 455) - (width/2)
  153. y = ((screen_height/2) + 20) - (height/2)
  154. NewWindow.resizable(0, 0)
  155. NewWindow.geometry("%dx%d+%d+%d" % (width, height, x, y))
  156. if 'UpdateWindow' in globals():
  157. UpdateWindow.destroy()
  158.  
  159. #===================FRAMES==============================
  160. FormTitle = Frame(NewWindow)
  161. FormTitle.pack(side=TOP)
  162. ContactForm = Frame(NewWindow)
  163. ContactForm.pack(side=TOP, pady=10)
  164. RadioGroup = Frame(ContactForm)
  165. Male = Radiobutton(RadioGroup, text="Male", variable=GENDER, value="Male", font=('arial', 14)).pack(side=LEFT)
  166. Female = Radiobutton(RadioGroup, text="Female", variable=GENDER, value="Female", font=('arial', 14)).pack(side=LEFT)
  167.  
  168. #===================LABELS==============================
  169. lbl_title = Label(FormTitle, text="Adding New Contacts", font=('arial', 16), bg="#66ff66", width = 300)
  170. lbl_title.pack(fill=X)
  171. lbl_firstname = Label(ContactForm, text="Firstname", font=('arial', 14), bd=5)
  172. lbl_firstname.grid(row=0, sticky=W)
  173. lbl_lastname = Label(ContactForm, text="Lastname", font=('arial', 14), bd=5)
  174. lbl_lastname.grid(row=1, sticky=W)
  175. lbl_gender = Label(ContactForm, text="Gender", font=('arial', 14), bd=5)
  176. lbl_gender.grid(row=2, sticky=W)
  177. lbl_age = Label(ContactForm, text="Age", font=('arial', 14), bd=5)
  178. lbl_age.grid(row=3, sticky=W)
  179. lbl_address = Label(ContactForm, text="Address", font=('arial', 14), bd=5)
  180. lbl_address.grid(row=4, sticky=W)
  181. lbl_contact = Label(ContactForm, text="Contact", font=('arial', 14), bd=5)
  182. lbl_contact.grid(row=5, sticky=W)
  183.  
  184. #===================ENTRY===============================
  185. firstname = Entry(ContactForm, textvariable=FIRSTNAME, font=('arial', 14))
  186. firstname.grid(row=0, column=1)
  187. lastname = Entry(ContactForm, textvariable=LASTNAME, font=('arial', 14))
  188. lastname.grid(row=1, column=1)
  189. RadioGroup.grid(row=2, column=1)
  190. age = Entry(ContactForm, textvariable=AGE, font=('arial', 14))
  191. age.grid(row=3, column=1)
  192. address = Entry(ContactForm, textvariable=ADDRESS, font=('arial', 14))
  193. address.grid(row=4, column=1)
  194. contact = Entry(ContactForm, textvariable=CONTACT, font=('arial', 14))
  195. contact.grid(row=5, column=1)
  196.  
  197.  
  198. #==================BUTTONS==============================
  199. btn_addcon = Button(ContactForm, text="Save", width=50, command=SubmitData)
  200. btn_addcon.grid(row=6, columnspan=2, pady=10)
Initializing the Application After finishing the function save the application as 'index.py'. This function will run the code and check if the main is initialize properly. To do that copy the code below and paste it inside the IDLE text editor.
  1. #============================INITIALIZATION==============================
  2. if __name__ == '__main__':
  3. Database()
  4. root.mainloop()

Tags

Add new comment