ghazigamer
ghazigamer

Reputation: 100

Tkinter text widget replace

Is there any method other than replace() method in tkinter where I can replace something specific for example: "hello", if I want to replace "h" with "a" it is going to be->"aello", problem with replace() method in tkinter is that it only replace for a range of text for the Text() widget.

In other words, can I replace a string by giving the characters to be replaced rather than the index of the characters to be replaced? For example, I would like to do something like entry.replace("hello", "goodbye") to automatically find the index of "hello" and replace those characters with "goodbye".

Upvotes: 2

Views: 742

Answers (1)

OysterShucker
OysterShucker

Reputation: 5531

My method for something like this, would be to extend the widget. Below is an example of extending the widget with 2 versions of replace. A regular version and a regex version.

import tkinter as tk, re
from typing import Pattern


class Text(tk.Text):
    @property 
    def text(self) -> str:
        return self.get('1.0', 'end')
        
    @text.setter
    def text(self, value:str):
        self.delete('1.0', 'end')
        self.insert('1.0', value)
        
    def __init__(self, master, **kwargs):
        tk.Text.__init__(self, master, **kwargs)
        
    def replace(self, find:str, sub:str):
        self.text = self.text.replace(find, sub)
        
    def reg_replace(self, find:Pattern, sub:str):
        self.text = find.sub(sub, self.text)
        

class Main(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)
        
        textfield = Text(self)
        textfield.grid(row=0, column=0, sticky='nswe', columnspan=2)
        
        re_find = re.compile('hello', re.I)
        find    = "Hello"
        sub     = "Goodbye"
        
        tk.Button(self, text='replace', command=lambda: textfield.replace(find, sub)).grid(row=1, column=0, sticky='e')
        tk.Button(self, text='regex replace', command=lambda: textfield.reg_replace(re_find, sub)).grid(row=1, column=1, sticky='e')
        

if __name__ == "__main__":
    root = Main()
    root.geometry('800x600')
    root.title("Text Replace Example")
    root.mainloop()

Upvotes: 1

Related Questions