Tkinter技术问题:如何检测Text组件输入文本是否匹配指定字符串
解决Tkinter Text组件文本匹配问题
你的代码里的问题在于,Tkinter的Text组件调用text.get(1.0, END)时,会返回包含末尾自动添加的换行符(\n)的内容。即使你插入的是'correct',实际获取到的是'correct\n',所以和'correct'直接对比永远不相等。
解决这个问题有两种常用方式:
方式一:移除末尾的换行符(推荐,不影响用户输入的其他空白)
使用rstrip('\n')只去掉末尾的换行,保留用户输入的其他空格和换行:def checking(): input_content = text.get(1.0, END).rstrip('\n') if input_content == 'correct': print('YESS') else: print('NOOOO') print(input_content)方式二:对比时包含换行符
直接和带换行的目标字符串对比,但这种方式只适用于固定单行内容的场景:def checking(): if text.get(1.0, END) == 'correct\n': print('YESS') else: print('NOOOO') print(text.get(1.0, END))
完整修改后的代码示例:
from tkinter import * window=Tk() def checking(): input_content = text.get(1.0, END).rstrip('\n') if input_content == 'correct': print('YESS') else: print('NOOOO') print(input_content) text=Text(window) gomb=Button(window, command=checking, text='Check') text.insert(1.0,'correct') text.pack() gomb.pack() window.mainloop()
内容的提问来源于stack exchange,提问作者Döme Kálmán Sarus
相关产品推荐
相关产品推荐

