Python: Simple Table Search Filter

Submitted by: 
Language: 
Visitors have accessed this post 427 times.

In this tutorial we will create a Simple Table Search Filter Using Python. Python is a computer programming language that lets work faster and convenient because of its user - friendly environment. Python supports packages and modules, which encourage a developer to program in a modularity and reusable way. So let's now 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

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)

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. #=====================================VARIABLES============================================
  2. SEARCH = StringVar()
  3. #=====================================FRAME================================================
  4. Top = Frame(root, width=500, bd=1, relief=SOLID)
  5. Top.pack(side=TOP)
  6. TopFrame = Frame(root, width=500)
  7. TopFrame.pack(side=TOP)
  8. TopForm= Frame(TopFrame, width=300)
  9. TopForm.pack(side=LEFT, pady=10)
  10. TopMargin = Frame(TopFrame, width=260)
  11. TopMargin.pack(side=LEFT)
  12. MidFrame = Frame(root, width=500)
  13. MidFrame.pack(side=TOP)
  14.  
  15. #=====================================LABEL WIDGET=========================================
  16. lbl_title = Label(Top, width=500, font=('arial', 18), text="Python: Simple Table Search Filter")
  17. lbl_title.pack(side=TOP, fill=X)
  18.  
  19. #=====================================ENTRY WIDGET=========================================
  20. search = Entry(TopForm, textvariable=SEARCH)
  21. search.pack(side=LEFT)
  22.  
  23. #=====================================BUTTON WIDGET========================================
  24. btn_search = Button(TopForm, text="Search", bg="#006dcc", command=Search)
  25. btn_search.pack(side=LEFT)
  26. btn_reset = Button(TopForm, text="Reset", command=Reset)
  27. btn_reset.pack(side=LEFT)
  28. #=====================================Table WIDGET=========================================
  29. scrollbarx = Scrollbar(MidFrame, orient=HORIZONTAL)
  30. scrollbary = Scrollbar(MidFrame, orient=VERTICAL)
  31. tree = ttk.Treeview(MidFrame, columns=("MemberID", "Firstname", "Lastname", "Address", "Age"), selectmode="extended", height=400, yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set)
  32. scrollbary.config(command=tree.yview)
  33. scrollbary.pack(side=RIGHT, fill=Y)
  34. scrollbarx.config(command=tree.xview)
  35. scrollbarx.pack(side=BOTTOM, fill=X)
  36. tree.heading('MemberID', text="MemberID",anchor=W)
  37. tree.heading('Firstname', text="Firstname",anchor=W)
  38. tree.heading('Lastname', text="Lastname",anchor=W)
  39. tree.heading('Address', text="Address",anchor=W)
  40. tree.heading('Age', text="Age",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=170)
  46. tree.column('#5', stretch=NO, minwidth=0, width=80)
  47. tree.pack()

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, address TEXT, age TEXT)")
  6. cursor.execute("SELECT * FROM `member`")
  7. if cursor.fetchone() is None:
  8. cursor.execute("INSERT INTO `member` (firstname, lastname, address, age) VALUES('Clea', 'Hela', 'San Francisco', '20')")
  9. cursor.execute("INSERT INTO `member` (firstname, lastname, address, age) VALUES('Thor', 'Jackson', 'San Aurora', '25')")
  10. cursor.execute("INSERT INTO `member` (firstname, lastname, address, age) VALUES('Naruto', 'Uzumaki', 'Konoha', '18')")
  11. cursor.execute("INSERT INTO `member` (firstname, lastname, address, age) VALUES('San', 'Juan', 'Peninsula', '55')")
  12. cursor.execute("INSERT INTO `member` (firstname, lastname, address, age) VALUES('Juan', 'Dela Cruz', 'San Juan', '22')")
  13. cursor.execute("INSERT INTO `member` (firstname, lastname, address, age) VALUES('Pedro', 'Bago', 'Bayan', '30')")
  14. conn.commit()
  15.  
  16. cursor.execute("SELECT * FROM `member` ORDER BY `lastname` ASC")
  17. fetch = cursor.fetchall()
  18. for data in fetch:
  19. tree.insert('', 'end', values=(data))
  20. cursor.close()
  21. conn.close()

Creating the Main Function
This is where the code will process the entry value and check if the data is exist within the database. Then display the data in the table when the button is clicked.

  1. def Search():
  2. if SEARCH.get() != "":
  3. tree.delete(*tree.get_children())
  4. conn = sqlite3.connect("pythontut.db")
  5. cursor = conn.cursor()
  6. cursor.execute("SELECT * FROM `member` WHERE `firstname` LIKE ? OR `lastname` LIKE ?", ('%'+str(SEARCH.get())+'%', '%'+str(SEARCH.get())+'%'))
  7. fetch = cursor.fetchall()
  8. for data in fetch:
  9. tree.insert('', 'end', values=(data))
  10. cursor.close()
  11. conn.close()
  12. def Reset():
  13. conn = sqlite3.connect("pythontut.db")
  14. cursor = conn.cursor()
  15. tree.delete(*tree.get_children())
  16. cursor.execute("SELECT * FROM `member` ORDER BY `lastname` ASC")
  17. fetch = cursor.fetchall()
  18. for data in fetch:
  19. tree.insert('', 'end', values=(data))
  20. cursor.close()
  21. conn.close()

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()

There you have it we just created a Simple Table Search Filter Using Python. I hope that simple tutorial help you for what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!!


Tags: 

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe>
  • You may insert videos with [video:URL]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.