0

This a simple code in which i have created a text area using tkinter and a menu in which there is a option of find and replace in which if user click on it then a gui will appear in which user will enter a word to whom they want to replace and then a word to whom they want replace with but till now i have just created a gui . But how can i replace word with a word given by user with the text of text area that i have created.

from tkinter import *
import tkinter.font as font
from tkinter import messagebox
root = Tk()
root.title("MyCodeEditor")
editor = Text()
editor.pack()
menu_bar = Menu(root)
def find_replace():
    f = Tk()
    f.title("Find and Replace")
    find_label = Label(f,text = "Find : ")
    replace_label = Label(f,text = "Replace : ")
    find_label.grid(row  = 0 , column = 0)
    replace_label.grid(row = 3 , column = 0)
    global find_enter
    global replace_enter
    find_enter = Entry(f,fg = "black" , background = "blue",borderwidth = 5,width = 40)

    replace_enter = Entry(f,fg = "black" , background = "blue", borderwidth = 5,  width =40 )
    find_enter.grid(row = 0 , column = 1)
    replace_enter.grid(row = 3 , column = 1)
    btn_replace = Button(f,text = 'Replace',fg = 'black',command = None)
    btn_replace.grid(row=0, column = 5)
format_bar = Menu(menu_bar , tearoff = 0)
format_bar.add_command(label = 'Find and Replace',command = find_replace)
menu_bar.add_cascade(label = 'Format' ,menu = format_bar )
root.config(menu = menu_bar)

root.mainloop()
  • There are multiple ways of doing it. I would suggest you look at [this](https://stackoverflow.com/a/19466754/11106801). Also do you know how to get the user's input out of `find_enter` and `replace_enter`? – TheLizzard Jun 09 '21 at 15:18
  • Now create a function that takes the two parameters: the text_to_search, word_to_replace, replacing_word and returns the text after replacement – Tarik Jun 09 '21 at 15:19
  • @Tarik you don't really need to create a function for that. It's simpler to just use: `text_to_search.replace(word_to_replace, replacing_word)` – TheLizzard Jun 09 '21 at 15:23
  • @TheLizzard I think it will not work because this will replace word inside find and replace gui not inside text area . Please run the code that i have provided then you will understand it better that what i mean with this statement . – Ayush saxena Jun 09 '21 at 15:52
  • Well, once you have this function ready, you call it with the text you get from the GUI, get the result and put it in the text area. – Tarik Jun 09 '21 at 18:25
  • @TheLizzard well for replacing that will work but what about findinf and replacing single words? Creating a function to find will also help with replacing. – Matiiss Jun 10 '21 at 09:02

1 Answers1

1

Here is a simple example (most of it is just the GUI looks, the main part is the actual replace method):

from tkinter import Tk, Text, Entry, Frame, Button, Toplevel, Label, Menu, TclError, IntVar

normal_font = ('comicsans', 10)


class FindAndReplace(Toplevel):
    def __init__(self, parent, text_widget: Text):
        Toplevel.__init__(self, parent)
        self.focus_force()
        self.title('Find and Replace')
        self.geometry('500x200')
        self.resizable(False, False)
        self.parent = parent
        self.widget = text_widget

        try:
            self.start_index = self.widget.index('sel.first')
            self.end_index = self.widget.index('sel.last')
        except TclError:
            self.start_index = '1.0'
            self.end_index = 'end'

        self.to_find = None
        self.to_replace = None

        # creating find entry

        find_frame = Frame(self)
        find_frame.pack(expand=True, fill='both', padx=20)

        Label(find_frame, text='Find:', font=normal_font).pack(side='left', fill='both', padx=20)
        self.find_entry = Entry(find_frame)
        self.find_entry.pack(side='right', expand=True, fill='x')

        # creating replace entry

        replace_frame = Frame(self)
        replace_frame.pack(expand=True, fill='both', padx=20)

        Label(replace_frame, text='Replace:', font=normal_font).pack(side='left', fill='both', padx=20)
        self.replace_entry = Entry(replace_frame)
        self.replace_entry.pack(side='right', expand=True, fill='x')

        # creating buttons

        button_frame = Frame(self)
        button_frame.pack(expand=True, fill='both', padx=20)

        Button(button_frame, text='Cancel', font=normal_font,
               command=self.destroy).pack(side='right', fill='x', padx=5)

        Button(button_frame, text='Replace', font=normal_font,
               command=self.replace).pack(side='right', fill='x', padx=5)

    def __find_get(self):
        self.to_find = self.find_entry.get()

    def __replace_get(self):
        self.to_replace = self.replace_entry.get()

    def replace(self):
        self.__find_get()
        self.__replace_get()

        if not self.to_replace:
            return

        length = IntVar()
        index = self.widget.search(self.to_find, self.start_index, stopindex=self.end_index, count=length)
        end_index = self.widget.index(index + f'+{length.get()}c')

        self.widget.delete(index, end_index)
        self.widget.insert(index, self.to_replace)


root = Tk()

menu_bar = Menu(root)
file_menu = Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label='File', menu=file_menu)
file_menu.add_command(label='Find and Replace', command=lambda: FindAndReplace(root, text))
root.config(menu=menu_bar)

text = Text(root)
text.pack()

root.mainloop()

Obviously some other functionality could be added such as replace all

Matiiss
  • 5,970
  • 2
  • 12
  • 29