Hi!

I'm very new to both python and Tkinter and would be thankful for some help.

i want to search a text document for a word and print each line that match the searchword in a text widget.

def ladda():
    fts = 'thefile.txt'
    file = open(fts,"r")
    text = file.readlines()
    file.close()

    keyword = re.compile("searchword")

    for line in text:
        result = keyword.search (line)
        if result:
            text.insert(INSERT, '\n' + line)

The error i get is:
text.insert(INSERT, '\n' + line)
TypeError: an integer is required

I have read about text.insert but dont get it.

/pluring

How do you import Tkinter?

How do you import Tkinter?

from Tkinter import *
import re
root = Tk()

Hmm, this little test program works just fine:

# a small re and Tkinter program to display lines from
# a data file that contain the word "searchword"

from Tkinter import *
import re

# create a test data file
data = """\
this line has the searchword
this line does not
searchword is in this line too
"""
filename = "mytestdata.txt"
fout = open(filename, "w")
fout.write(data)
fout.close()


root = Tk()

text = Text(root, width=50, height=12, bg='yellow')
text.pack()

keyword = re.compile("searchword")

for line in file(filename):
    result = keyword.search (line)
    if result:
        text.insert(INSERT, '\n' + line)


root.mainloop()

BTW, don't use 'file' as a name for a variable, since there is a Python function named file()

It appears that you are using "text" twice.

##--- here "text" is the list of records from the file
    text = file.readlines()
    file.close()

    keyword = re.compile("searchword")

##--- here you are reading from the list of records which is named "text"
    for line in text:
        result = keyword.search (line)
        if result:
##--- here you are trying to "INSERT, '\n' + line" into the
##     list named "text", which can not be done
            text.insert(INSERT, '\n' + line)

Thank you!

Works with your code.

But i still don't understand why my solution did not work with text.insert?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.