简体   繁体   English

Tkinter 文本小部件替换

[英]Tkinter text widget replace

Is there any method other than replace() method in tkinter where I can replace something specific for example: "hello", if I want to replace "h" with "a" it is going to be->"aello", problem with replace() method in tkinter is that it only replace for a range of text for the Text() widget.除了 tkinter 中的replace()方法之外,还有什么方法可以替换特定的东西,例如:“你好”,如果我想用“a”替换“h”,它将是->“aello”,问题是tkinter 中的replace()方法是它只替换Text()小部件的一系列文本。

In other words, can I replace a string by giving the characters to be replaced rather than the index of the characters to be replaced?换句话说,我可以通过给出要替换的字符而不是要替换的字符的索引来替换字符串吗? For example, I would like to do something like entry.replace("hello", "goodbye") to automatically find the index of "hello" and replace those characters with "goodbye".例如,我想做诸如entry.replace("hello", "goodbye")类的entry.replace("hello", "goodbye")来自动查找“hello”的索引并将这些字符替换为“goodbye”。

My method for something like this, would be to extend the widget.我的类似方法是扩展小部件。 Below is an example of extending the widget with 2 versions of replace .下面是使用 2 个版本的replace扩展小部件的示例。 A regular version and a regex version.一个普通版本和一个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.

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