实现从TXT文件检索结果返回TKinter GUI,点击搜索无响应
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
- Invalid regex method:
re.query()doesn't exist in Python'sremodule. You need to usere.search()to check if your search term appears in the line (withre.Ifor case insensitivity). - Missing content in insert call:
findings.insert(INSERT)doesn't specify what text to add—you need to pass the matching line. - Unmanaged file handling: You're manually opening the file but relying on
close()which can fail if an error occurs. Using awithstatement automatically handles file closure. - No result clearing: Each search appends to the text box instead of starting fresh, leading to messy results over time.
- 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
- Index error risk: If any line in
data.txtdoesn't have a tab character (\t),line.split("\t")will create a list with only one element. Trying to accesselements[1]will throw anIndexErrorand stop the function entirely. - Unconditional newlines: You're inserting a newline every loop, even when no match is found, which creates empty lines in the results.
- Unnecessary string conversion:
str(lookfor.get())is redundant becauseEntry.get()already returns a string. - 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
相关产品推荐
相关产品推荐

