You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 01:35:16