Метод Text.replace() ошибка TypeError: Text.replace() missing 1 required positional argument: 'chars'

from tkinter import *
def find(event=False):
    txt_edit.tag_remove("found", "1.0", END)
    s = findEntry.get()
    if (s):
        idx = "1.0"
        while 1:
            idx = txt_edit.search(s, idx, nocase = 1, stopindex = END)
            if not idx: break
            lastidx = "% s+% dc" % (idx, len(s))
            txt_edit.tag_add("found", idx, lastidx)
            idx = lastidx
        txt_edit.tag_config("found", foreground="red", background="blue")
    findEntry.focus_set()

def replace(event=False):
    txt_edit.replace(index1=str(findEntry.get()), index2=str(replaceEntry.get()))
def closefr(event=False):
    findaNdreplace.destroy()
def findandreplace(event=False):
    global findaNdreplace, findEntry, findButton, replaceEntry, replaceButton, txt_edit
    findaNdreplace = Tk()
    findaNdreplace["bg"]="LightGrey"
    txt_edit = Text()
    txt_edit.pack()
    findEntry = Entry(findaNdreplace)
    findEntry.pack(fill=X)
    findButton = Button(findaNdreplace, text="Найти", command=find, background="LightGrey")
    findButton.pack(fill=X)
    replaceEntry = Entry(findaNdreplace)
    replaceEntry.pack(fill=X)
    replaceButton = Button(findaNdreplace, text="Заменить", command=replace, background="LightGrey")
    replaceButton.pack(fill=X)
    findEntry.bind("<Key>", find)
    findaNdreplace.protocol("WM_DELETE_WINDOW", closefr)
    findaNdreplace.mainloop()
findandreplace()

После чего получаю:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\miros\AppData\Local\Programs\Python\Python310-32\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "D:\Z\VarTexter2\VarTexter_v.2.0.py", line 1034, in replace
    txt_edit.replace(index1=str(findEntry.get()), index2=str(replaceEntry.get()))
TypeError: Text.replace() missing 1 required positional argument: 'chars'

Что вписать в 3-ий аргумент?


Ответы (1 шт):

Автор решения: insolor

Метод replace у виджета Text заменяет текст между указанными индексами на другой текст и добавляет теги переданные в дополнительных параметрах. См. докстроку метода replace:

def replace(self, index1, index2, chars, *args): # new in Tk 8.5
    """Replaces the range of characters between index1 and index2 with
    the given characters and tags specified by args.

    See the method insert for some more information about args, and the
    method delete for information about the indices."""
    self.tk.call(self._w, 'replace', index1, index2, chars, *args)

Т.е. например text.replace("1.0", "1.2", "asdf") заменит первые два символа в первой строке текстового поля на asdf.

Чтобы заменить какой-то текст на другой текст, нужно вытащить текст полностью (text.get(1.0, END)), методом replace строки заменить текст, потом перезаписать текст обратно в текстовое поле (тем же методом replace виджета Text с указанием индексов начала и конца текста):

all_text = txt_edit.get("1.0", END)
all_text = all_text.replace(findEntry.get(), replaceEntry.get())
txt_edit.replace("1.0", END, all_text)
→ Ссылка