为何从tkinter文本框获取字符串时搜索功能失效?
问题
从Tkinter文本框提取字符串执行搜索时功能失效,但直接将关键词定义为字符串常量时搜索正常。最小复现代码如下:
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" # 取消注释这行搜索正常 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()
原因
Tkinter的Text组件使用get("1.0", "end")获取内容时,会自动在返回的字符串末尾添加一个换行符\n。比如你在filterbox中输入"apple",实际拿到的关键词是"apple\n",和手动定义的"apple"不匹配,导致搜索失效。
解决方案
获取文本内容时,将"end"替换为"end-1c",end-1c表示末尾位置往前偏移1个字符,这样就能去掉多余的换行符:
def searchcall(): # 用end-1c替代end,去除末尾多余换行 textboxcontent=textExample.get("1.0","end-1c") keyword=filterbox.get("1.0","end-1c") # keyword="apple" # 现在可以注释掉这行,搜索正常运行 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)
内容的提问来源于stack exchange,提问作者Nivatius
相关产品推荐
相关产品推荐

