簡體   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