0

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()
Nivatius
  • 260
  • 1
  • 13
  • 1
    If you want a single line input, use `Entry` instead of `Text` widget for `filterbox`. – acw1668 Jul 26 '22 at 10:10
  • The solution is to change `filterbox` to `filterbox.insert(1.0,"apple\n")`. The Text end tag inserts a line feed on the last entry. Now it works! – Derek Jul 28 '22 at 06:03
  • @Derek the idea is that the user would provide the contents via GUI. the insert statements are to provide an example. – Nivatius Jul 28 '22 at 07:12

1 Answers1

2

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')
Nivatius
  • 260
  • 1
  • 13