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

实现从TXT文件检索结果返回TKinter GUI,点击搜索无响应

Fixing Your Tkinter Search Button Issues

Let's walk through why your search button isn't responding and fix both of your code versions. I'll break down the problems and show you the corrected code for each case.

Issues with Your First Code Snippet

  1. Invalid regex method: re.query() doesn't exist in Python's re module. You need to use re.search() to check if your search term appears in the line (with re.I for case insensitivity).
  2. Missing content in insert call: findings.insert(INSERT) doesn't specify what text to add—you need to pass the matching line.
  3. Unmanaged file handling: You're manually opening the file but relying on close() which can fail if an error occurs. Using a with statement automatically handles file closure.
  4. No result clearing: Each search appends to the text box instead of starting fresh, leading to messy results over time.
  5. No empty input check: If the user clicks search with an empty input, it still runs unnecessary code.

Corrected First Code

import re
from tkinter import *

def query():
    # Clear previous results first
    findings.delete(1.0, END)
    search_term = lookfor.get().strip()
    
    # Exit early if input is empty
    if not search_term:
        return
    
    # Use `with` to auto-manage the file
    with open("data.txt", "r") as datafile:
        for line in datafile:
            # Check if the search term exists in the line (case-insensitive)
            if re.search(search_term, line, re.I):
                findings.insert(END, line)

root = Tk()
lookfor = Entry(root)
lookfor.pack(padx=5, pady=5)
Button(root, text="Search", command=query).pack(padx=5, pady=2)
findings = Text(root, width=50, height=15)
findings.pack(padx=5, pady=5)
root.mainloop()

Issues with Your Second Code Snippet

  1. Index error risk: If any line in data.txt doesn't have a tab character (\t), line.split("\t") will create a list with only one element. Trying to access elements[1] will throw an IndexError and stop the function entirely.
  2. Unconditional newlines: You're inserting a newline every loop, even when no match is found, which creates empty lines in the results.
  3. Unnecessary string conversion: str(lookfor.get()) is redundant because Entry.get() already returns a string.
  4. Same missing result clearing: Just like the first snippet, results stack instead of being refreshed.

Corrected Second Code

from tkinter import *

def query():
    # Clear previous results
    findings.delete(1.0, END)
    search_term = lookfor.get().strip()
    
    if not search_term:
        return
    
    with open("data.txt", "r") as datafile:
        for line in datafile:
            line = line.strip()
            # Skip empty lines in the data file
            if not line:
                continue
            
            elements = line.split("\t")
            # Make sure we have at least two elements before accessing indexes
            if len(elements) >= 2:
                if search_term in elements[0]:
                    findings.insert(END, f"{elements[1]}\n")
                elif search_term in elements[1]:
                    findings.insert(END, f"{elements[0]}\n")

root = Tk()
lookfor = Entry(root)
lookfor.pack(padx=5, pady=5)
Button(root, text="Search", command=query).pack(padx=5, pady=2)
findings = Text(root, width=50, height=15)
findings.pack(padx=5, pady=5)
root.mainloop()

Both corrected versions should now respond when you click the Search button, show clean results, and avoid common errors like file leaks or index exceptions.

内容的提问来源于stack exchange,提问作者Chomsky

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:29:44