Search code examples
pythontkintertextboxline

How to find line number of searched string in Tkinter Textbox and then insert string just before


let's say i have a tkinter Textbox like this :

textbox =

Hello world !
Life is good on earth
Winter is already there

How do i search for "good", get the line number and insert something on the line number just before ?

Expected result :

Hello world !
New sentence inserted here
Life is good on earth
Winter is already there

I know how to use the .find("good") method to get the number of characters before "good" is reached but since i want to be able to use the textbox.insert() i need the line number (not the number of characters) like 1.0 to specify where i want to insert the new sentence in the textbox .


Solution

  • You may play with the tkinter index:

    from tkinter import *
     
    root = Tk()
    fram = Frame(root)
    Label(fram,text='Text to find:').pack(side=LEFT)
    edit = Entry(fram)
    edit.pack(side=LEFT, fill=BOTH, expand=1)
    edit.focus_set()
    butt = Button(fram, text='Find') 
    butt.pack(side=RIGHT)
    fram.pack(side=TOP)
    text = Text(root)
    text.insert('1.0','''Hello world !
    Life is good on earth
    Winter is already there''')
    text.pack(side=BOTTOM)
     
    def find():
        s = edit.get()
        if s:
            idx = '1.0'
            idx = text.search(s, idx, nocase=1, stopindex=END)
            if idx:
                text.insert(idx.split('.')[0]+'.0', 'New sentence inserted here\n')
        edit.focus_set()
    butt.config(command=find) 
    root.mainloop()