简体   繁体   English

替换 Tkinter 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.我想知道是否有办法替换 Tkinter Text 小部件中特定单词的所有实例。
Eg例如

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'我想按下一个按钮,用“python”这个词替换“how”这个词的所有实例

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.我可能需要使用 search() 函数,但我不确定从那里开始做什么。

Thanks for your help :)谢谢你的帮助 :)

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):输出(GIF):

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM