Python Tkinter search box

In this tutorial, we will are going to discuss the Python Tkinter search box. Here we will learn how to create a search box in Python Tkinter and we will also cover different examples related to the Tkinter Search Box. And, also cover these topics.

  • Python Tkinter search box
  • Python Tkinter search button
  • Python Tkinter search text
  • Python Tkinter Listbox search
  • Python Tkinter tree view search
  • Python Tkinter Combobox search
  • Python Tkinter search file

Python Tkinter search box

In this section, we will learn how we can create a search box in Python Tkinter.

A search box is a search field that accepts the user input. The user enters the text or letter in the search box which they want to search.

Code:

In the following code, we create a widget inside the widget we create a search box and Find button for finding the text.

  • Label() is used to display a field of text or images.
  • Button() is used for searching the text with a single click.
  • txt.insert() is used to insert some text in the text field.
  • txt.search() is used to search the text.
from tkinter import *

ws = Tk()
Frm = Frame(ws)
Label(Frm,text='Enter Word to Find:').pack(side=LEFT)
modify = Entry(Frm)

modify.pack(side=LEFT, fill=BOTH, expand=1)

modify.focus_set()

buttn = Button(Frm, text='Find')
buttn.pack(side=RIGHT)
Frm.pack(side=TOP)

txt = Text(ws)

txt.insert('1.0','''Enter here...''')
txt.pack(side=BOTTOM)


def find():
	
	txt.tag_remove('found', '1.0', END)
	ser = modify.get()
	if ser:
		idx = '1.0'
		while 1:
			idx = txt.search(ser, idx, nocase=1,
							stopindex=END)
			if not idx: break
			lastidx = '%s+%dc' % (idx, len(ser))
			
			txt.tag_add('found', idx, lastidx)
			idx = lastidx
		txt.tag_config('found', foreground='blue')
	modify.focus_set()
buttn.config(command=find)

ws.mainloop()

Output:

In the following output, we see that the user enter the text and click on the Find button. After clicking they find the text which they want to search.

Python Tkinter search box
Python Tkinter search box

Read: Python Tkinter On-Off Switch

Python Tkinter search button

In this section, we will learn how to create a search button in Python Tkinter.

The search button is used for submitting the search. Users enter text in the search box. After entering the text click on the search button for submitting their search and find the text which they want.

Code:

In the following code, we create a window ws=Tk() inside this window we create a label, button.

Label() is used to display a field of text.
Button() is used for submitting the text.
txt.insert() is used to insert some text in the text field.
txt.search() is used to search the text.

from tkinter import *

ws = Tk()
Frm = Frame(ws)
Label(Frm,text='Enter to search:').pack(side=LEFT)
modify = Entry(Frm)

modify.pack(side=LEFT, fill=BOTH, expand=1)

modify.focus_set()

buttn = Button(Frm, text='Search')
buttn.pack(side=RIGHT)
Frm.pack(side=TOP)

txt = Text(ws)

txt.insert('1.0','''Enter Text here...''')
txt.pack(side=BOTTOM)


def find():
	
	txt.tag_remove('found', '1.0', END)
	ser = modify.get()
	if ser:
		idx = '1.0'
		while 1:
			idx = txt.search(ser, idx, nocase=1,
							stopindex=END)
			if not idx: break
			lastidx = '%s+%dc' % (idx, len(ser))
			
			txt.tag_add('found', idx, lastidx)
			idx = lastidx
		txt.tag_config('found', foreground='blue')
	modify.focus_set()
buttn.config(command=find)

ws.mainloop()

Output:

After running this code, we get the following output in which we see the user enter the text. After entering the text, click on the search button for submitting the search and find the text which they want.

Python Tkinter search button
Python Tkinter search button Output

Read: Python Tkinter Validation examples

Python Tkinter search text

In this section, we will learn how to search a text in Python Tkinter.

Search text is to find the text in between the paragraph. The user enters the text which they want to search in the search box and click on the search button. After clicking on the button the user gets the text which they search for.

Code:

In the following code, we create a window inside the window we add a search box and search button for searching a text.

from tkinter import *

ws = Tk()
Frm = Frame(ws)
Label(Frm,text='Enter Word to Find:').pack(side=LEFT)
modify = Entry(Frm)

modify.pack(side=LEFT, fill=BOTH, expand=1)

modify.focus_set()

buttn = Button(Frm, text='Find')
buttn.pack(side=RIGHT)
Frm.pack(side=TOP)

txt = Text(ws)

txt.insert('1.0','''English comprehension passage is the good test of your language skills. The questions in the reading comprehension exercise are mostly inference based...''')
txt.pack(side=BOTTOM)


def find():
	
	txt.tag_remove('found', '1.0', END)
	ser = modify.get()
	if ser:
		idx = '1.0'
		while 1:
			idx = txt.search(ser, idx, nocase=1,
							stopindex=END)
			if not idx: break
			lastidx = '%s+%dc' % (idx, len(ser))
			
			txt.tag_add('found', idx, lastidx)
			idx = lastidx
		txt.tag_config('found', foreground='blue')
	modify.focus_set()
buttn.config(command=find)

ws.mainloop()

Output:

After running the following code, we get the following output in which the user enters the text in the search box. After clicking on the search button we get the text which user wants.

Python Tkinter search text
Python Tkinter search text Output

Read: Python Tkinter notebook Widget

Python Tkinter Listbox search

In this section, we will learn how to create a Listbox search in Python Tkinter.

Listbox is used to display a list of items to the user. And permits the user to select the items from a list. Users click inside the list box on an item to select it.

Code:

In the following code, we create a window that displays the list of items to the user. And also create an entry widget to enter the list items for search.

Entry() is used to entering the list item for search from the Listbox.

from tkinter import *


def Scankey(event):
	
	val = event.widget.get()
	print(val)
	

	if val == '':
		data = list
	else:
		data = []
		for item in list:
			if val.lower() in item.lower():
				data.append(item)				

	
	Update(data)


def Update(data):
	

	listbox.delete(0, 'end')

	# put new data
	for item in data:
		listbox.insert('end', item)



list = ('C','C++','Java',
	'Python','Perl',
	'PHP','ASP','JS' )

ws = Tk()


entry = Entry(ws)
entry.pack()
entry.bind('<KeyRelease>', Scankey)


listbox = Listbox(ws)
listbox.pack()
Update(list)

ws.mainloop()

Output:

In the following output, we see the Listbox that displays the list of items to the user. When the user wants to search for an item from the list. Users enter the item name in the search bar and the item they want to search is seen on the top.

Python Tkinter Listbox search
Python Tkinter Listbox search Output

Read: Python Tkinter Events

Python Tkinter treeview search

In this section, we will learn how we can create a Treeview search in Python Tkinter.

Treeview refers to hierarchical representation. It gives an improved look to the data columns. In the Tkinter Treeview search, we want to search the names present in this Treeview. The user enters the name in the search box and clicks on the search button if the name is present in the treeview show on the top.

Code:

In the following code, we create the connection between the student table and the search box.

  • conn = connect(“data1.db”) creating the open database.
  • curs = conn.cursor() create cursor(connecting user to database).
  • curs.execute(db1) after inserting the the data we want to execute the data.
  • conn.commit() saving inserting data intodatabase.
  • conn.rollback()return the last changes made to the database.
from tkinter import *
from tkinter import ttk
from tkinter.messagebox import *
from sqlite3 import *


ws = Tk()                       
ws.title("Python Guides")        
ws.geometry("750x700+400+50")  
ws.resizable(0, 0)            
view_window      



conn = None

conn = connect("data1.db")

  
curs = conn.cursor()


db = "create table student(rno int primary key, name text)"
curs.execute(db)


if conn is not None:
    conn.close()    



conn = None


conn = connect("data1.db")


curs = conn.cursor()


db1 = "insert into student values(1,'Pauline')"
db2 = "insert into student values(2,'Dexter')"
db3 = "insert into student values(3,'Melba')"
db4 = "insert into student values(4,'Roxanne')"
db5 = "insert into student values(5,'Mary')"
db6 = "insert into student values(6,'Andrew')"
db7 = "insert into student values(7,'Renata')"


curs.execute(db1)
curs.execute(db2)
curs.execute(db3)
curs.execute(db4)
curs.execute(db5)
curs.execute(db6)
curs.execute(db7)


conn.commit()


if conn is not None:
    conn.close()


def show():
    ws_ent.delete(0, END)     
    ws_ent.focus()
    treeview.selection()
    conn = None
    try:
        conn = connect("data1.db")    
        cursor = conn.cursor()
        db = "select * from student"   
        cursor.execute(db)

        fetchdata = treeview.get_children()       
        for elements in fetchdata:
            treeview.delete(elements)
    

        data = cursor.fetchall()
        for d in data:
            treeview.insert("", END, values=d)

        conn.commit()
    except Exception as e:
        showerror("Fail", e)
        conn.rollback()
    finally:
        if conn is not None:
            conn.close()
def search():
    treeview.selection()
    fetchdata = treeview.get_children()
    for f in fetchdata:
        treeview.delete(f)
    conn = None
    try:
        conn = connect("data1.db")
        core = conn.cursor()
        db = "select * from student where name = '%s' "
        name = ws_ent.get()
        if (len(name) < 2) or (not name.isalpha()):
            showerror("fail", "invalid name")
        else:
            core.execute(db %(name))
            data = core.fetchall()
            for d in data:
                treeview.insert("", END, values=d)
            
    except Exception as e:
        showerror("issue", e)

    finally:
        if conn is not None:
            conn.close()
def reset():
    show()  



scrollbarx = Scrollbar(ws, orient=HORIZONTAL)  
scrollbary = Scrollbar(ws, orient=VERTICAL)    
treeview = ttk.Treeview(ws, columns=("rollno", "name"), show='headings', height=22)  
treeview.pack()
treeview.heading('rollno', text="Roll No", anchor=CENTER)
treeview.column("rollno", stretch=NO, width = 100) 
treeview.heading('name', text="Name", anchor=CENTER)
treeview.column("name", stretch=NO)
scrollbary.config(command=treeview.yview)
scrollbary.place(x = 526, y = 7)
scrollbarx.config(command=treeview.xview)
scrollbarx.place(x = 220, y = 460)
style = ttk.Style()
style.theme_use("default")
style.map("Treeview")


ws_lbl = Label(ws, text = "Name", font=('calibri', 12, 'normal'))
ws_lbl.place(x = 290, y = 518)
ws_ent = Entry(ws,  width = 20, font=('Arial', 15, 'bold'))
ws_ent.place(x = 220, y = 540)
ws_btn1 = Button(ws, text = 'Search',  width = 8, font=('calibri', 12, 'normal'), command = search)
ws_btn1.place(x = 480, y = 540)
ws_btn2 = Button(ws, text = 'Reset',  width = 8, font=('calibri', 12, 'normal'), command = reset)
ws_btn2.place(x = 600, y = 540)


show()  
ws.mainloop()

Output:

In the following output, we see the user enter the name in the search box which they want to search. After entering the name click on the search button. After clicking on them the name is shown on the top and then reset again and search another one.

Python Tkinter Treeview
Python Tkinter Treeview Output

Read: Python Tkinter Listbox

Python Tkinter Combobox search

In this section, we will learn how to create a Combobox search in Python Tkinter.

Combobox defines as a dropdown list or list box. We can either type the item name which we want to search or directly select the item from the dropdown list menu.

Syntax:

combo = Combobox(master,option=value)

Code:

In the following code, we use the .ttk import Combobox library for importing the Combobox list

  • Entry() where the user can enter the item in the entrybox.They want to search from the Combobox.
  • Button() is used for submitting the text.
from tkinter import *
from tkinter.ttk import Combobox

ws = Tk()
ws.title("Python Guides")
ws.geometry("200x200")


def search_items():
    search_value = variable.get()
    if search_value == "" or search_value == " ":
        combo['values'] = item_names
    else:
        value_to_display = []
        for value in item_names:
            if search_value in value:
                value_to_display.append(value)
        combo['values'] = value_to_display


item_names = list([str(a) for _ in range(100) for a in range(10)])

combo = Combobox(ws, state='readonly')
combo['values'] = item_names
combo.pack()

variable=StringVar()
entry1 = Entry(ws, textvariable=variable)
entry1.pack()

button = Button(ws, text="search", command=search_items)
button.pack()

ws.mainloop()

Output:

In the following output, we see the Combobox the user clicks on the item they want to choose. The chosen item is shown in the entry box.

Python Tkinter Combobox search
Python Tkinter Combobox search

We also enter the item in the entry box we want to search. As we showed in this image user enter the item and click on the search button.

Python Tkinter combobox search1
Python Tkinter Combobox search1

After click on the search button, the User gets the item from the Combobox.

Python Tkinter Combobox search2
Python Tkinter Combobox search2

Read: Python Tkinter messagebox

Python Tkinter search file

In this section, we will learn how to create the search file option in Python Tkinter.

A search file is an option for searching the important file that is stored in a specified category. By clicking on the button.

Code:

In the following code, we create a window ws = Tk() inside the window we add a button with the text “Select file”. By clicking on the button we reach the search file location and search the file.

  • filedialog.askopenfile() function shows the dialog box that allows the user to select the file and return the file that the user selected.
  • lambda function only has a single expression.
from tkinter import *
from tkinter import filedialog
ws = Tk()
ws.title("Python Guides")
ws.geometry('200x200')

def ask_to_open_file():
   display = filedialog.askopenfile(initialdir="/")
   print(display)
   for j in display:
      print(j)

button = Button(ws, text ='Select file', command = lambda:ask_to_open_file())
button.pack(pady=10)
ws.mainloop()

Output:

After running this code we get the following output we see a button is placed on the widget. For searching a file we click on the select file button.

Python Tkinter search file
Python Tkinter search file

After clicking on the button the dialogue box is open where we can search the file we need and select to open the file.

Python Tkinter search file1
Python Tkinter search file1

After click on open, we see the text inside the file shown in the command prompt with the location of the file where the file is saved.

Python Tkinter search file2
Python Tkinter search file2

You may also like to read the following Tkinter tutorials.

So, in this tutorial, we discuss the Python Tkinter search box and we have also covered different examples related to its implementation. Here is the list of examples that we have covered.

  • Python Tkinter search box
  • Python Tkinter search button
  • Python Tkinter search text
  • Python Tkinter Listbox search
  • Python Tkinter tree view search
  • Python Tkinter Combobox search
  • Python Tkinter search file