Skip to content
Advertisement

Search the data on the text file and Printing in GUI with Tkinter

I am writing a python program to search the data on the text file in GUI

The search function normally gives the result (in CLI). I want to use it with Tkinter, but when I pull the input with the Tkinter Entry function, my search function does not work.

Whatever I write, it outputs the data in the entire text file. I think the problem is in the if msg.get() in line:

The search function is below.

def search():
    with open(r"loglar.txt", 'r') as fp:
        for l_no, line in enumerate(fp):
            lineNum = l_no + 1
            # search string
            if msg.get() in line:
                lineNumber = ('Line Number:', lineNum)
                lineWord = ('Line:', line)
                print(lineNumber)
                print(lineWord)

Also this is my Tkinter Function

def getInfo():
msg = entry.get()
print(type(msg))
print(msg)
search()

Advertisement

Answer

def parse_date(date_str):
    # format mm/dd/yy HH:MM:SS[.NNNNNN]
    date_fmt = '%m/%d/%y %H:%M:%S'
    if '.' in date_str:
        date_fmt += '.%f'
    return datetime.strptime(date_str, date_fmt)






#function to search string in text
def search(msg, startingDate, endingDate, beforeLine, varBefore):
    # clear current result
    text.delete('1.0', 'end')
    with open('OAM.log', 'r', encoding='latin1') as fp:
        global l_no
        for l_no, line in enumerate(fp, 1):
            if msg and msg not in line:
                # does not contain search message, skip it
                continue
            if startingDate or endingDate:
                # get the timestamp
                timestamp = parse_date(line[1:25])
                # within startingDate and endingDate ?
                if startingDate and timestamp < startingDate:
                    # before given starting date, skip it
                    continue
                if endingDate and timestamp > endingDate:
                    # after given ending date, skip it
                    continue
                
            # insert the log
            text.insert('end', ' n ')
            text.insert('end', f'Line Number: {l_no} Log: {line}')
            text.insert('end', ' n ')



def getInfo():
    msg = edit.get() if var1.get() == 1 else None
    startingDate = parse_date(tarih1.get()) if var2.get() == 1 else None
    endingDate = parse_date(tarih2.get()) if var3.get() == 1 else None
    afterLine = afterEntry.get() if varAfter.get() == 1 else None
    beforeLine = beforeEntryVar.get() if varBefore.get() == 1 else None
    afterLine = afterEntry.get() if varAfter.get() == 1 else None
    
    
    search(msg, startingDate, endingDate, beforeLine, afterLine)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement