[英]Tkinter text widget replace
除了 tkinter 中的replace()
方法之外,还有什么方法可以替换特定的东西,例如:“你好”,如果我想用“a”替换“h”,它将是->“aello”,问题是tkinter 中的replace()
方法是它只替换Text()
小部件的一系列文本。
换句话说,我可以通过给出要替换的字符而不是要替换的字符的索引来替换字符串吗? 例如,我想做诸如entry.replace("hello", "goodbye")
类的entry.replace("hello", "goodbye")
来自动查找“hello”的索引并将这些字符替换为“goodbye”。
我的类似方法是扩展小部件。 下面是使用 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.