我的方法是扩展小部件。下面是使用 2 个版本的 replace 扩展小部件的示例。普通版和regex 版。
import tkinter as tk, re
from typing import Pattern
class Text(tk.Text):
@property
def text(self) -> str:
return self.get('1.0', 'end')
@text.setter
def text(self, value:str):
self.delete('1.0', 'end')
self.insert('1.0', value)
def __init__(self, master, **kwargs):
tk.Text.__init__(self, master, **kwargs)
def replace(self, find:str, sub:str):
self.text = self.text.replace(find, sub)
def reg_replace(self, find:Pattern, sub:str):
self.text = find.sub(sub, self.text)
class Main(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
textfield = Text(self)
textfield.grid(row=0, column=0, sticky='nswe', columnspan=2)
re_find = re.compile('hello', re.I)
find = "Hello"
sub = "Goodbye"
tk.Button(self, text='replace', command=lambda: textfield.replace(find, sub)).grid(row=1, column=0, sticky='e')
tk.Button(self, text='regex replace', command=lambda: textfield.reg_replace(re_find, sub)).grid(row=1, column=1, sticky='e')
if __name__ == "__main__":
root = Main()
root.geometry('800x600')
root.title("Text Replace Example")
root.mainloop()