繁体   English   中英

替换 Tkinter Text 小部件中的特定单词

[英]Replace specific word in Tkinter Text widget

我想知道是否有办法替换 Tkinter Text 小部件中特定单词的所有实例。
例如

假设这是我的文本小部件:
Hello how are you? How is the weather?

我想按下一个按钮,用“python”这个词替换“how”这个词的所有实例

Hello python are you? python is the weather?

我可能需要使用 search() 函数,但我不确定从那里开始做什么。

谢谢你的帮助 :)

这是一个工作代码:

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

在此处输入图片说明

暂无
暂无

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

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