Nivatius
Nivatius

Reputation: 270

searching in strings from tk-inter text fails

Why does the search fail when taking a string from a tk-inter text box? The search works fine if I define the keyword as a string.

Minimal example:

import tkinter as tk
root = tk.Tk()
string="banana\napplepie\napple\n"

def searchcall():
 
    textboxcontent=textExample.get("1.0","end")
    keyword=filterbox.get("1.0","end")
    keyword="apple" # search works as expected

    print("keyword",keyword)
    print("is keyword in textbox",keyword in textboxcontent)
    for elem in textboxcontent.split():
        print("seaching for",keyword,"in",elem,keyword in elem)
 
        

textExample=tk.Text(root, height=10)
textExample.insert(1.0,string)
textExample.pack()
filterbox=tk.Text(root, height=1)
filterbox.insert(1.0,"apple")
filterbox.pack()
btnRead=tk.Button(root, height=1, width=11, text="search", 
                    command=searchcall)

btnRead.pack()
root.mainloop()

Upvotes: 0

Views: 66

Answers (1)

Nivatius
Nivatius

Reputation: 270

The problem is that tk inter appends a line break "\n" at the end when you read the contents of a widget. Remove the "\n" at the end of the strings. For example, with strip

keyword=filterbox.get("1.0","end").strip()

you can also choose to read everything but the last character like this (source):

keyword=filterbox.get("1.0",'end-1c')

Upvotes: 2

Related Questions