Open In App

Search String in Text using Python-Tkinter

Last Updated : 26 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Tkinter is the standard GUI library for Python. It provides a powerful object-oriented interface to the Tk GUI toolkit. In this article, we’ll see how to search for a specific string in a given text window using Tkinter.
NOTE : For more detailed information on Tkinter, refer to Python GUI – Ttkinter
Method to create user-defined function to search(def find) 
An inner loop will search the text widget for all instances of each word, tagging them for highlighting. The termination condition for the loop is that the current word was not found in the widget. Then, after all, words have been tagged, set their color. 
 

  • Declare a variable s and get the string input of the user to be searched in the text( in this case the string is typed in ‘edit’ text box window) 
     
  • Initialize index value as 1. 
     
  • Initialize inner loop. 
     
  • Using .search() search for the desired string (in this case s) in the given text and update the current index value till the end of the text. 
     
  • Last Index value is the addition of the current index and length of the string. 
     
  • Add ‘found’ tag from index 1 to last index whenever a desired string is found in between. 
     
  • Change focus to find button 
     
  • Once find button is pressed. the string with ‘found’ tags, the string is highlighted in red. 
     
  • use .mainloop() for termination as any user will terminate the program 
     

Example 1: 
 

Python3




#Python Program to search string in text using Tkinter
 
from tkinter import *
 
#to create a window
root = Tk()
 
#root window is the parent window
fram = Frame(root)
 
#adding label to search box
Label(fram,text='Text to find:').pack(side=LEFT)
 
#adding of single line text box
edit = Entry(fram)
 
#positioning of text box
edit.pack(side=LEFT, fill=BOTH, expand=1)
 
#setting focus
edit.focus_set()
 
#adding of search button
butt = Button(fram, text='Find'
butt.pack(side=RIGHT)
fram.pack(side=TOP)
 
#text box in root window
text = Text(root)
 
#text input area at index 1 in text window
text.insert('1.0','''Type your text here''')
text.pack(side=BOTTOM)
 
 
#function to search string in text
def find():
     
    #remove tag 'found' from index 1 to END
    text.tag_remove('found', '1.0', END)
     
    #returns to widget currently in focus
    s = edit.get()
    if s:
        idx = '1.0'
        while 1:
            #searches for desired string from index 1
            idx = text.search(s, idx, nocase=1,
                              stopindex=END)
            if not idx: break
             
            #last index sum of current index and
            #length of text
            lastidx = '%s+%dc' % (idx, len(s))
             
            #overwrite 'Found' at idx
            text.tag_add('found', idx, lastidx)
            idx = lastidx
         
        #mark located string as red
        text.tag_config('found', foreground='red')
    edit.focus_set()
butt.config(command=find)
 
#mainloop function calls the endless loop of the window,
#so the window will wait for any
#user interaction till we close it
root.mainloop()


OUTPUT : 

<img src="https://media.geeksforgeeks.org/wp-content/uploads/20200327124102/tkinter2.png" alt="Search String in Text using Python-Tkinter
“>

The larger text box is for the text input and the smaller text box is for the string input that needs to be found in the given text and once found, it is marked in red.
Example 2: 
 

Python3




#Python Program to search string in text using Tkinter
 
from tkinter import *
 
root = Tk()
fram = Frame(root)
Label(fram,text='Text to find:').pack(side=LEFT)
edit = Entry(fram)
edit.pack(side=LEFT, fill=BOTH, expand=1)
edit.focus_set()
butt = Button(fram, text='Find'
butt.pack(side=RIGHT)
fram.pack(side=TOP)
 
 
text = Text(root)
text.insert('1.0','''Type your text here''')
text.pack(side=BOTTOM)
 
 
 
def find():
     
    text.tag_remove('found', '1.0', END)
    s = edit.get()
    if s:
        idx = '1.0'
        while 1:
            idx = text.search(s, idx, nocase=1,
                              stopindex=END)
            if not idx: break
            lastidx = '%s+%dc' % (idx, len(s))
            text.tag_add('found', idx, lastidx)
            idx = lastidx
       text.tag_config('found', foreground='red')
    edit.focus_set()
butt.config(command=find)
root.mainloop()


OUTPUT : 

<img src="https://media.geeksforgeeks.org/wp-content/uploads/20200327124532/tkinter21.png" alt="Search String in Text using Python-Tkinter
“>

 



Previous Article
Next Article

Similar Reads

Difference Between The Widgets Of Tkinter And Tkinter.Ttk In Python
Python offers a variety of GUI (Graphical User Interface) frameworks to develop desktop applications. Among these, Tkinter is the standard Python interface to the Tk GUI toolkit. Tkinter also includes the 'ttk' module, which enhances the visual appeal and functionality of the applications. In this article, we will cover the differences, providing a
4 min read
How to Set Text of Tkinter Text Widget With a Button?
Prerequisite: Python GUI – tkinter Text Widget is used where a user wants to insert multi-line text fields. In this article, we are going to learn the approaches to set the text inside the text fields of the text widget with the help of a button. Approach: Using insert and delete methodImport the Tkinter module.Create a GUI window.Create our text w
2 min read
How to wrap text within Tkinter Text Box?
In this article, we will see that how can we wrap the text in the TKinter Text-Box using the Tkinter module Called textWrap Module. The textwrap module can be used for wrapping and formatting plain text. This module provides formatting of the text by adjusting the line breaks in the input paragraph. Example 1: Firstly We will import the Tkinter Lib
2 min read
Python - SpongeBob Mocking Text Generator GUI using Tkinter
Prerequisites : Introduction to tkinter | SpongeBob Mocking Text Generator Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In this article, we will learn how to cre
4 min read
Python - UwU text convertor GUI using Tkinter
Prerequisites :Introduction to tkinter | UwU text convertor Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and easiest way to crea
4 min read
Python - English (Latin) to Hindi (Devanagiri) text convertor GUI using Tkinter
Prerequisites : Introduction to tkinter | Text transliteration from English to Indian languages – Using indic-transliterationPython offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python
4 min read
Text to speech GUI convertor using Tkinter in Python
Prerequisite: Introduction to Tkinter Tkinter is the standard GUI library for Python. Python when combined with tkinter provides a fast and easy way to create GUI applications.By this library we can make a compelling choice for building GUI applications in Python, especially for applications where a modern sheen is unnecessary, and the top priority
3 min read
Build a basic Text Editor using Tkinter in Python
Tkinter is a Python Package for creating GUI applications. Python has a lot of GUI frameworks, but this is the only framework that’s built into the Python standard library. It has several strengths; it’s cross-platform, so the same code works on Windows, macOS, and Linux. It is lightweight and relatively painless to use compared to other frameworks
4 min read
Read a text file using Python Tkinter
Graphical User Interfaces (GUIs) are an essential aspect of modern software development, providing users with interactive and visually appealing applications. Python's Tkinter library is a robust tool for creating GUIs, and in this article, we will delve into the process of building a Tkinter application that reads and displays the content of a tex
3 min read
Tkinter | Adding style to the input text using ttk.Entry widget
Tkinter is a GUI (Graphical User Interface) module which is widely used to create GUI applications. It comes along with the Python itself. Entry widgets are used to get the entry from the user. It can be created as follows- entry = ttk.Entry(master, option = value, ...) Code #1: Creating Entry widget and taking input from user (taking only String d
2 min read
Article Tags :
Practice Tags :