1

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 :)

stovfl
  • 14,998
  • 7
  • 24
  • 51
jack.py
  • 362
  • 8
  • 23

1 Answers1

2

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

Nouman
  • 6,947
  • 7
  • 32
  • 60