Python Tkinter中添加嵌套while循环实现同名多结果返回
解决Tkinter搜索重复姓名返回所有对应数字的问题
先给你修复后的可运行代码,直接替换你原有的逻辑就行:
import tkinter as tk def search_name(): target_name = name_entry.get().strip() result_list = [] # 打开文本文件,读取所有行 with open("data.txt", "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line: continue # 拆分姓名和数字,兼容多空格分隔的情况 parts = line.split() if len(parts) >= 2: name, num = parts[0], parts[1] if name == target_name: result_list.append(num) # 将结果显示到输入框,用逗号分隔 result_entry.delete(0, tk.END) if result_list: result_entry.insert(0, ", ".join(result_list)) else: result_entry.insert(0, "未找到匹配姓名") # 创建Tkinter窗口 root = tk.Tk() root.title("姓名搜索工具") # 输入姓名的组件 tk.Label(root, text="输入姓名:").pack(pady=5) name_entry = tk.Entry(root, width=20) name_entry.pack(pady=5) # 搜索按钮 search_btn = tk.Button(root, text="搜索", command=search_name) search_btn.pack(pady=5) # 显示结果的输入框 tk.Label(root, text="对应数字:").pack(pady=5) result_entry = tk.Entry(root, width=30) result_entry.pack(pady=5) root.mainloop()
关键修改说明
- 废弃了容易出错的嵌套while循环,改用单循环遍历所有行,把匹配到的数字都存入列表,最后统一展示
- 用
with open语法自动管理文件,避免手动关闭文件的麻烦 - 增加了空行过滤和拆分后的长度判断,避免文件格式异常导致报错
- 结果用逗号分隔展示,清晰直观
你的文本文件示例(data.txt)
bob 18
alice 22
bob 19
charlie 30
运行后输入bob,结果框会显示18, 19,完美返回所有对应数字。
内容的提问来源于stack exchange,提问作者Marco
相关产品推荐
相关产品推荐

