Search code examples
pythontkintertkinter.text

Replace specific word in Tkinter Text widget


I was wondering if there's a way to replace all instances of a specific word in the Tkinter Text widget.
E.g.

Pretend this is my text widget:
Hello how are you? How is the weather?

I want to press a button and replace all instances of the word 'how' with the word 'python'

Hello python are you? python is the weather?

I'll probably need to use the search() function, but I wasn't sure what to do from there.

Thanks for your help :)


Solution

  • Here is a working code:

    import tkinter as tk
    
    
    text = "Hello how are you? How is the weather?"
    def onclick():
        text_widget.delete("1.0", "end")   #Deletes previous data
        text_widget.insert(tk.END, text.replace("how","python").replace("How","python"))   #Replacing How/how with python
    
    root = tk.Tk()
    text_widget = tk.Text(root)
    text_widget.insert(tk.END, text)  #inserting the data in the text widget
    text_widget.pack()
    
    button = tk.Button(root, text = "Press me!", command = onclick)
    button.pack()
    
    root.mainloop()
    

    Output (GIF):

    enter image description here