JavaEar 专注于收集分享传播有价值的技术资料

Tkinter text search box 'bad text index'

I am creating a search box for a text editor using the text.search("1.0", entry.get(), stopindex="end") command. The problem is I get the error TclError: bad text index "text here". I followed the question here for guidance on the search() function but I don't know what is wrong. How do I fix this to make the search box work? Here is my code:

from Tkinter import *
import tkMessageBox
import tkFileDialog

class Main(object):
    def __init__(self, root):
        root.title("PyText")

        self.f1=Frame(root)
        self.f1.grid(row=1)

        #Main text widget
        self.t1=Text(root)
        self.t1.config(width=90, height=40, undo=True, bg="#41494B", highlightbackground="#41494B", foreground="white")
        self.t1.grid(row=2, padx=10, pady=10)

        self.search=Entry(self.f1, highlightbackground="#2b373a")
        self.search.grid(column=2, row=0)

        self.search_button=Button(self.f1, highlightbackground="#2b373a", command=lambda: self.t1.search("1.0", self.search.get(), stopindex="end"), text="Search")
        self.search_button.grid(row=3, column=0)

root = Tk()
root.config(bg="#2b373a")
app = Main(root)
root.mainloop()

1个回答

    最佳答案
  1. You have transposed the arguments to search(). The first argument needs to be the search query, and the second argument needs to be the starting index.

    self.t1.search("1.0", self.search.get(), stopindex="end")
    

    should be:

    self.t1.search(self.search.get(), "1.0", stopindex="end")