我想知道Tkinter文本小部件中是否可以替换特定单词的所有实例。
例如
假装这是我的文本小部件:
Hello how are you? How is the weather?
我想按下一个按钮,并将单词“ how”的所有实例替换为单词“ python”
Hello python are you? python is the weather?
我可能需要使用search()函数,但是我不确定该怎么做。
感谢您的帮助:)
答案 0 :(得分: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):