Заменить определенное слово в виджете Tkinter Text
Мне было интересно, есть ли способ заменить все экземпляры определенного слова в виджете Tkinter Text.
Например
Притворись, что это мой текстовый виджет:Hello how are you? How is the weather?
Я хочу нажать кнопку и заменить все вхождения слова "как" словом "питон"
Hello python are you? python is the weather?
Вероятно, мне нужно будет использовать функцию search(), но я не был уверен, что делать дальше.
Спасибо за вашу помощь:)
1 ответ
Решение
Вот рабочий код:
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()
Выход (GIF):