1

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

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

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

Hello python are you? python is the weather?

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

谢谢你的帮助 :)

4

1 回答 1

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

在此处输入图像描述

于 2019-08-04T06:19:14.223 回答